PREV NEXT
- Inheritance is the process of inheriting the attributes (data member) and behaviour (methods) of an existing class into a new class. (i.e. Inheritance is a process in which one class acquires the features of already existing class)
- The new class which inherits all characteristics of the existing class is called as Sub class.
- The existing class which is being inherited is called as SuperClass.
- Inheritance can be achieved by adding ‘extends’ keyword near the sub class name and then followed by the superclass (class which has to be inherited).
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class A { display(){ System.out.println(In class A); } } class B extends A { } //Inside main method of a class B obj =new B(); obj.display(); // Output: In class A } } |
- The subclass can access the attributes and behaviour of the superclass in addition to its own attributes and behaviour.
- Consider a class vehicle which has 3 subclasses – car, ship, flight.
- The methods start(), stop(), parking() are common to all the vehicles and hence they are added in the vehicle class.
- The car class contains driving() method and the methods start(), stop(), parking() which are inherited from the vehicle class.
- Similarly the classes ship and flight have the methods specific to them in addition to the methods inherited from the vehicle class.
- A class cannot extend more than one class. Multiple inheritance is not allowed in Java unlike in C++. But one super class can have multiple sub class.
Class A extends B, C // not allowed
Class M extends A Class N extends A Class O extends A // class A has 3 subclasses M, N, O |
Multi level Inheritance:
A subclass can be inherited by another class.
Example:
1 2 3 4 5 6 7 8 9 10 11 |
class A{ } class B extends A{ } //class B can access the properties of class A class C extends B{ } //class C can access the properties of both class A & B |
Member Access in Inheritance:
A subclass can access all the members of the superclass except those which are declared as private.
Example:
Class A{ private int a1; int a2; ..} Class B extends A{ a1=5; //not allowed a2 = 10; ..} |