OOP Inheritance Introduction#
What Is The Inheritance In OOP?#
Inheritance
in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. It is an important part of OOP.- The idea behind
inheritance
in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also. - Inheritance represents the IS-A relationship which is also known as a
parent-child
relationship. - Using
inheritance
in Java will help us:- Overriding methods.
- Code reusability.
Java Inheritance Syntax#
- The
extends
keyword indicates that you are making a new class that derives from an existing class. The meaning of "extends" is to increase the functionality. - In the terminology of Java, a class which is inherited is called a
parent
orsuperclass
, and the new class is calledchild
orsubclass
.
Inheritance Example#
- Let's define a parent class
Animal
as below
Animal.java | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
- Then create a subclass which is
extends
fromAnimal
Dog.java | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
- Now, test the child class
Dog
and you will see the child class can inherit attribute name and method eat from parent classAnimal
. Moreover, It is also@Override
the methodsleep()
from it's parent.
JavaInheritanceMain.java | |
---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
1 2 3 4 |
|