Inheritance In Java : Introduction
- Inheritance is an important feature of object oriented programming paradigm. It defines relation(parent and child) between two or more classes and so as it does in java and is called as inheritance in java.
- We can correlate inheritance with a family hierarchy. You inherit your parents’ properties which forms a hierarchy.
- Another example can be car, bike, rickshaw, truck all these derives from class Vehicle.
- Similarly, Inheritance in java is the ability of a class to derive properties of another class. We can also say that inheritance is the property of an object to derive properties of other objects.
extends Keyword :
extends keyword in Java is used to implement inheritance. We will be using extends keyword in Java program to implement inheritance.
For example :
class B extends A , here extends keyword is used to create a child class of class A.
Inheritance in Java : Types
1) Single Inheritance : It means, child class inherits from single parent class.
2) Multilevel Inheritance : In multilevel inheritance, child class inherits from a class(intermediate class) which itself inherits from a super class.
- In the above example we have used object of class C to access methods of class A and class B .
3) Hierarchical Inheritance : In this type of inheritance more than one child class derives from a single base class.
Note-1 : Multiple inheritance is not supported in Java. Multiple inheritance in OOP is a type of inheritance in which once child class inherits from more than one parent class.
Note-2 : In Java Multiple inheritance is not supported because it may become ambiguous in case if more than one parent class have same type of method.
Which members of parent class are available to child class?
- When a child class inherits parent class it generally inherits all members of its parent class, but it cannot access those members of parent class that have been declared private.
- Hence the conclusion is that private members of parent class are not accessible in child class. Let us take an example.
- As you can see in above output private members of parent class are not accessible by object of child class even on inheriting. Hence, compile time error is generated.
Inheritance In Java : Advantages
- Code re-usability.
- For extending properties of a class.
For example : Suppose class B derive properties and behavior of class A, then class B is called child class/sub class and class A is called parent class/super class.