Monday, 18 December 2017

Chapter 2 : Inheritance

Chapter 2: Inheritance

Inheritance is a mechanism in which one object (the Child) acquires all properties & behaviors of other (the parent) object.

Using inheritance we can create new class built upon existing classes.

When we inherit from an existing class we can reuse the properties and methods of an existing class (parent class/super class). Also we can add new properties and methods to the child class (sub class).

Inheritance represents IS-A relationship, also known as parent-child relationship.

Syntax of Java Inheritance


Class child_class_name extends parent_class_name
{
// Properties & methods of child class
}  

Inheritance Example

class Citizen {  
 string name = “Raj” ;
Int SSN = 876554226784;
}  
class Employee extends Citizen {  
Float Salary=190000.64;  
 public static void main(String args[]){  
   Employee E=new Employee ();  
System.out.println("Employee name is:"+E.bonus);  
System.out.println("Employee SSN is:"+E.SSN);     
System.out.println("Employee salary is:"+E.salary);  
   
}  
}  

Types of Inheritance in Java

There are 3 types of inheritance in java 1) Single 2) Multilevel 3) Hierarchical . Below picture illustrates these 3 types of inheritance.

Fig 2.1 Inheritance types in Java

Note: Multiple inheritance is not supported in java through class. In java programming, multiple inheritance is supported through interface only.

Lets us understand, Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.

Fig 2.2 Multiple Inheritance not supported in Java

In the above figure 2.2, class C is inherited using both class A and class B (multiple inheritance). Both class A and class B have same method called add().

Now suppose we create object of the class C and call method add() there will be ambiguity about which method to call, whether to call method of class A or class B.


C obj = new C()

obj.add()  // ambiguity error

Above scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class. Since compile time errors are better than run time errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error.