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:-
class
ParentClass
{
//variables and methods
} public class
ChildClass
extends
ParentClass
{ 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:-
class
Machine
{ public void
start
() { System.out.println("
Machine Starting !
"); } } class
Camera extends Machine
{ public void
snap
() { System.out.println("
Camera Snapping !
"); } } public class
MyClass
{ public static void main(String[] args) { Camera
obj
= 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:-
class
Machine
{ public void
start
() { System.out.println("
Machine Starting !
"); } } class
Camera extends Machine
{ public void
snap
() { System.out.println("
Camera Snapping !
"); } } class
Mobile extends Camera
{ public void
capture
() { System.out.println("
Mobile Capturing !
"); } } public class
MyClass
{ public static void main(String[] args) { Mobile
obj
= 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:-
class
Machine
{ public void
start
() { System.out.println("
Machine Starting !
"); } } class
Camera extends Machine
{ public void
snap
() { System.out.println("
Camera Snapping !
"); } } class
Mobile extends Machine
{ public void
capture
() { System.out.println("
Mobile Capturing !
"); } } public class
MyClass
{ public static void main(String[] args) { Mobile
obj
= new Mobile();
obj
.
start
();
// obj.snap(); //generates error as snap() is undefined for Mobile
obj
.
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 class
Parent
{
//code
} public class
MyClass extends Parent
{
//cannot be inherited , generates error
public static void main(String[] args) { } }