Single Inheritance:
- Definition: In single inheritance, a class (subclass) inherits from only one parent class (superclass).
- Example: Class A extends Class B. Here, Class A inherits properties and behaviors (methods) from Class B, and there is only one direct parent class.
Example in Java:
class Animal { void eat() { System.out.println("This animal eats food."); } } class Dog extends Animal {
void bark() {
System.out.println("The dog barks.");
}
}
public class Main {
public static void main(String args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.bark(); // Defined in Dog
}
}
- Output:
This animal eats food.
The dog barks.
Multiple Inheritance:
- Definition: In multiple inheritance, a class inherits from more than one parent class. This can lead to ambiguity if multiple parent classes have methods with the same name.
- Supported in Java?: Java does not support multiple inheritance with classes to avoid complexity and ambiguity (like the "diamond problem"). However, multiple inheritance is allowed through interfaces.
Multiple Inheritance in Java using Interfaces:
Java allows a class to implement multiple interfaces, which is a form of multiple inheritance.
Example in Java:
interface Animal { void eat(); } interface Bird {
void fly();
}
class Bat implements Animal, Bird {
public void eat() {
System.out.println("The bat eats insects.");
}
public void fly() {
System.out.println("The bat flies.");
}
}
public class Main {
public static void main(String args) {
Bat bat = new Bat();
bat.eat(); // From Animal interface
bat.fly(); // From Bird interface
}
}
- Output:
The bat eats insects.
The bat flies.
Key Differences:
- Single Inheritance: A class inherits from only one class.
- Multiple Inheritance: A class can inherit from multiple classes (supported via interfaces in Java).
In Java, multiple inheritance is handled using interfaces to avoid the ambiguity associated with inheriting from multiple classes.