OOP Inheritance Introduction#
What Is The Inheritance In OOP?#
Inheritancein 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
inheritancein 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-childrelationship. - Using
inheritancein Java will help us:- Overriding methods.
- Code reusability.
Java Inheritance Syntax#
- The
extendskeyword 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
parentorsuperclass, and the new class is calledchildorsubclass.
Inheritance Example#
- Let's define a parent class
Animalas 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
extendsfromAnimal
| Dog.java | |
|---|---|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
- Now, test the child class
Dogand you will see the child class can inherit attribute name and method eat from parent classAnimal. Moreover, It is also@Overridethe 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 | |