Inheritance

Inheritance in java

  • Inheritance: Inheritance can be defined as process in which one class (child class) can acquire properties (fields and methods) of another class (parent class).
  • Parent Class: The class whose properties are inherited is called parent class or base class or super class.
  • Child Class: The class which inherits properties of others is called child class or derived class or subclass.

 

inheritance-1

Syntax of inheritance.

public class Superclass_name

{

//methods and fields

}
public Subclass_name extends Superclass_name

{

//methods and fields

}
  • Inheritance represents IS-A type relationship.
  • Inheritance can be achieved in java by using of extends keyword.
  • When extending a class, you can add new properties and methods, and you can change the behavior of existing methods.

Use of Inheritance

  • You can declare a method with the same signature and write new code for it(Method Overriding)
  • For Code Re-usability.
  • The biggest advantage of Inheritance is that, code in base class need not be rewritten in the derived class.

Examples of Inheritance:

Example 1:

public class Animal

{

}
public class Mammal extends Animal

{

}

public class Reptile extends Animal

{

}

public class Dog extends Mammal

{

}

Example 2:

class Employee

{

float salary=40000;

}

class Programmer extends Employee

{

int bonus=10000;

public static void main (String args[])

{

Programmer p=new Programmer();    

System.out.println("Programmer salary is:"+p.salary);

System.out.println ("Bonus of Programmer is:"+p.bonus);

}

}

Output

Programmer salary is:40000.0

Bonus of programmer is:10000

 

Types of inheritance java:

There are following types of inheritance:

  • Single
  • Multilevel
  • Multiple
  • Hierarchical
  • Hybrid

inheritance-2

inheritance-3

Multiple inheritances is not possible in java.

  • When we inherit properties of two or more classes or object in one class or object then it is called as Multiple Inheritance.
  • But in java it is not supported.
  • If we inherit properties of two or more classes then there will be ambiguity that which method should call.
  • Compile time error occur
  • Hence multiple inheritance is not possible in java.