Inheritance
- Inheritance is a mechanism that allows a class to inherit the properties and behaviors of another class.
- The derived class inherits all the members of the base class and can also add its own members or override the inherited ones.
- Every class we'll ever use or ever write will inherit from class Object (except of course class Object itself).
- The two most common reasons to use inheritance are:
- To promote code reuse.
- To use polymorphism.
- IS-A is a way of saying, "this thing is a type of that thing."
- We express the IS-A relationship in Java through the keywords extends (for class inheritance) and implements (for interface implementation).
- "Car extends Vehicle" means "Car IS-A Vehicle".
- HAS-A relationships are based on usage, rather than inheritance.
- Class A HAS-A B if code in class A has a reference to an instance of class B.
IS-A and HAS-A Relationships
Single Inheritance
Subclass inherit the features of one superclass.
Multilevel Inheritance
A derived class will be inheriting a base class and as well as the derived class also act as the base class to other class.
Hierarchical Inheritance
One class serves as a superclass for more than one subclass.
Multiple Inheritance
One class have more than one superclass and inherit features from all parent classes. Java doesn't support multiple inheritances with classes. In Java, we can achieve multiple inheritances only through interfaces.
Note: Some languages (like C++) allow a class to extend more than one other class. The reason that Java's creators chose not to allow multiple inheritance is that it can become quite messy.
Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn't support multiple inheritances with classes, hybrid inheritance is also not possible with classes.
Comments
Post a Comment