Inheritance is a fundamental concept in object-oriented programming (OOP) that allows one class to inherit the properties and behaviors (fields and methods) of another class. In Java, there are several types of inheritance, each serving a different purpose:
1. **Single Inheritance**: In single inheritance, a class (the subclass or derived class) inherits from only one other class (the superclass or base class). This is the most straightforward form of inheritance.
“`java
class Animal {
void eat() {
System.out.println(“This animal eats food.”);
}
}
class Dog extends Animal {
void bark() {
System.out.println(“The dog barks.”);
}
}
“`
Here, `Dog` inherits from `Animal`.
2. **Multilevel Inheritance**: In multilevel inheritance, a class inherits from another class, which in turn inherits from another class, and so on. This forms a chain of inheritance.
class Animal {
void eat() {
System.out.println(“This animal eats food.”);
}
}
class Mammal extends Animal {
void breathe() {
System.out.println(“This mammal breathes air.”);
}
}
class Dog extends Mammal {
void bark() {
System.out.println(“The dog barks.”);
}
}
Here, `Dog` inherits from `Mammal`, and `Mammal` inherits from `Animal`.
3. **Hierarchical Inheritance**: In hierarchical inheritance, multiple classes inherit from a single superclass. This allows different classes to share the common behavior defined in the superclass.
class Animal {
void eat() {
System.out.println(“This animal eats food.”);
}
}
class Dog extends Animal {
void bark() {
System.out.println(“The dog barks.”);
}
}
class Cat extends Animal {
void meow() {
System.out.println(“The cat meows.”);
}
}
Here, both `Dog` and `Cat` inherit from `Animal`.
4. **Multiple Inheritance (through interfaces)**: Java does not support multiple inheritance of classes due to the diamond problem (where ambiguity arises from multiple inheritance). However, Java allows a class to implement multiple interfaces, which can be used to achieve a form of multiple inheritance.
interface Animal {
void eat();
}
interface Pet {
void play();
}
class Dog implements Animal, Pet {
public void eat() {
System.out.println(“The dog eats.”);
}
public void play() {
System.out.println(“The dog plays.”);
}
}
Here, `Dog` implements both `Animal` and `Pet` interfaces.
5. **Hybrid Inheritance**: Hybrid inheritance is a combination of two or more types of inheritance. Java does not support hybrid inheritance directly with classes due to complexities and ambiguities. However, you can achieve hybrid inheritance through interfaces and abstract classes.
abstract class Animal {
abstract void eat();
}
interface Pet {
void play();
}
class Dog extends Animal implements Pet {
public void eat() {
System.out.println(“The dog eats.”);
}
public void play() {
System.out.println(“The dog plays.”);
}
}
Here, `Dog` combines abstract class inheritance and interface implementation.
Each type of inheritance serves a specific design purpose and helps organize and reuse code efficiently.
Leave a Reply