Define inheritance. Discuss the benefits of using inheritance. Discuss multiple inheritance with suitable example.
Inheritance is a concept that acquires the properties from one class to another class. A class can inherit attributes and methods from another class. The class that inherits the properties is known as the sub-class or the child class. The class from which the properties are inherited is known as the superclass or the parent class.
Benefits of Inheritance
• Inheritance helps in code reuse. The child class may use the code defined in the paren class without re-writing it.
• Inheritance can save time and effort as the main code need not be written again.
• Inheritance provides a clear model structure that is easy to understand.
• An inheritance leads to less development and maintenance costs.
• With inheritance, we will be able to override the methods of the base class so that the meaningful implementation of the base class method can be designed in the derived class. An inheritance leads to less development and maintenance costs.
• In inheritance base class can decide to keep some data private so that it cannot be altered by the derived class.
Multiple Inheritance
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes. Java does not support multiple inheritances with classes. In java, we can achieve multiple inheritances only through Interfaces. In the following example Class Animal is derived from interface AnimalEat and AnimalTravel.
interface AnimalEat {
void eat();
} interface AnimalTravel
{
void travel();
}
class Animal implements AnimalEat, AnimalTravel
{
public void eat()
{
System.out.printIn("Animal is eating");
}
public void travel()) {
System.out.println("Animal is travelling");
}
Comments
Post a Comment