Object Oriented Programming - JAVA- Inheritance

 Object Oriented Programming - JAVA👽

    In this blog we will discuss about inheritance in java programming. Through this blog, you can get an idea about what is "inheritance", why we use inheritance, how we use inheritance in coding. So, let's start.



Inheritance.....

The process of relating one class to another is called inheritance.  In inheritance we need to know mainly two types of classes.
  • Super class
  • Sub class

Superclass is the class that gives its properties and behavior, in other words variables and methods. The superclass is also called the parent class.
Subclasses inherit the variables and methods of the superclass. A subclass is also called a child class.
Sub class can take all the things of super class but super class cannot take things of sub class. If the super class has private thing, sub class can't get that.


Sub classes have new variables and methods that not in super class. Let me give simple example for it. Father has a car. when the inheritance, his son gets the car. and also son has a bike his own.
Inheritance allows programmers to, 
  • create classes that build on existing classes,
  • specify new implementations that maintain those behaviors,
  • reuse code,
  • independently extend the original software through common classes and interfaces.
How to use inheritance in the java coding?

We use the keyword "extends" to inherit super class to sub class. 

    class Employee {
            private String employee_name;
            String company_name;
            void salary(){
            
            }
    }

    class JavaProgrammer extends Employee {
            int device;
            void discount(){
            
            }
    }

    class Text {
        public static void main(String args[]){
            JavaProgrammer obj = new JavaProgrammer();
            obj.device;
            obj.discount();
            obj.company_name;
            obj.salary();

        }
    }

  • Employee class inherits JavaProgrammer class.
  • Now, JavaProgrammer class have discount method and device variable.
  • JavaProgrammer class get salary method and company_name variable.
  • JavaProgrammer class can't get the private variable employee_name.
With inheritance we can use one object to access the superclass through the subclass.

See you in the next blog to discuss about Method Overriding .


Comments

Popular posts from this blog

Sorting Algorithms - JAVA👽

Object Oriented Programming - JAVA- class boundary, variable types, modifiers, java main method

Object Oriented Programming - JAVA- Method Overriding