Java Inheritance (Part 3)
Java Inheritance
Just as a child inherits properties of its parents , in the same way a class can inherit methods and variables of another class.
The class acting as a parent from which other classes are derived is called as Base class / Parent Class / Super Class.
The class acting as a child which derives the properties of parent class is called as Sub class / Child class.
Why use Inheritance ?
- It is useful for code reusability: reuse attributes and methods of an existing class when you create a new class.
Syntax:-
classParentClass{//variables and methods} public classChildClassextendsParentClass{ public static void main(String[] args) {//variables and methods} }
The keyword extends is used to indicate that you are making a child class by inheriting properties of parent class.
Types Of Inheritance
1. Single-level inheritance
When a class inherits another class , the inheritance is called as single level inheritance.
eg:-
classMachine{ public voidstart() { System.out.println("Machine Starting !"); } } classCamera extends Machine{ public voidsnap() { System.out.println("Camera Snapping !"); } } public classMyClass{ public static void main(String[] args) { Cameraobj= new Camera();obj.start();obj.snap(); } }
Output:-
Machine Starting !
Camera Snapping !
2. Multi-level inheritance
When there is a chain of inheritance , the type is called as multi-level inheritance.
eg:-
classMachine{ public voidstart() { System.out.println("Machine Starting !"); } } classCamera extends Machine{ public voidsnap() { System.out.println("Camera Snapping !"); } } classMobile extends Camera{ public voidcapture() { System.out.println("Mobile Capturing !"); } } public classMyClass{ public static void main(String[] args) { Mobileobj= new Mobile();obj.start();obj.snap();obj.capture(); } }
Output:-
Machine Starting !
Camera Snapping !
Mobile Capturing !
3. Hierarchical inheritance
When two or more classes inherit a single class i.e a parent class has two or more child classes then it is called hierarchical inheritance.
eg:-
classMachine{ public voidstart() { System.out.println("Machine Starting !"); } } classCamera extends Machine{ public voidsnap() { System.out.println("Camera Snapping !"); } } classMobile extends Machine{ public voidcapture() { System.out.println("Mobile Capturing !"); } } public classMyClass{ public static void main(String[] args) { Mobileobj= new Mobile();obj.start();// obj.snap(); //generates error as snap() is undefined for Mobileobj.capture(); } }
Output:-
Machine Starting !
Mobile Capturing !
The Final Keyword
If you want a class which cannot be inherited by other classes , we declare classes as final.
final classParent{//code} public classMyClass extends Parent{//cannot be inherited , generates errorpublic static void main(String[] args) { } }



