Inheritance in
java is the most used and most important topic of OOP. Inheritance is defined
as a process where one object acquires the properties of another object. With
the help of inheritance, information can be made manageable in a hierarchical
order.
Extends and Implements are the two
keywords that we come across when we are dealing with inheritance. By using
these keywords one object can acquire properties of another object. Inheritance
is an IS-A type of relationship.
Types of inheritance
–
Inheritance is
broadly classified into 4 categories:
·
Single
Inheritance.
·
Multiple
Inheritance.
·
Multi-level
Inheritance.
·
Hierarchical
Inheritance.
Single Inheritance –
When a class inherits the properties of another class, it is an example of Single Inheritance. In the below example Dog class inherits the properties of Animal class.
Multiple-level Inheritance –
It is the concept of object oriented programming where one base class inherits the superclass and the same base class acts as Superclass for another base class. In the below example, Animal is the base class, Mammal is extending the Animal class and Mammal class is the base class for Cat class.
Hierarchical Inheritance
–
It is the concept of Object Oriented programming where one superclass is inherited by multiple base classes or in other words, multiple base classes inherit the single superclass. In the below example, Animal class is extended by Cat, Dog and Tiger class.
Multiple Inheritance
–
It is the concept of Object Oriented programming where
one class can extend properties of one or more base class. Java
does not support Multiple Inheritance. In the below example, cat class is extending both Animal
as well as Mammal class.
IS-A relation:
Child object
IS-A type of parent type object. Let’s see how the “extend” keyword is used to maintain inheritance.
Now, based on the
above example, the following are true in object oriented words:
• Animal is a superclass of mammal class.
• Animals are the superclass of the reptile class.
• Mammal and reptile are subclasses of the animal class.
• Dog is a subclass of both mammal and animal classes.
Now, if we
consider the IS-A relation, we can say:
• Mammal IS-A Animals
• The reptile is an IS-A animal
• Dog IS-A Mammal.
• Hence: Dog IS-A Animal as well.
Except for the private properties of
the superclass, the sub-class will be able to inherit all the properties with
the use of extends keyword.
The instanceOf keyword-
The instanceOf
variable is used to determine whether the sub-class is the instance of the superclass.
Consider the following example:
The output will
be:
true
true
true
Related Articles:
1. Core java interview questions.
2. Java 8 interview questions.
3. Internal working of Hashmap in java.
0 Comments