MDS 371 Exercise
MDS 371 Exercise
Multiple Inheritance
Multiple inheritance refers to a feature in object-oriented programming where a
class can inherit properties and behaviours from more than one parent class. This
allows the child class to have characteristics of multiple super classes.
For example, in C++, multiple inheritance is possible:
class A {
public:
void showA() { count << "Class A"; }
};
class B {
public:
void showB() { count << "Class B"; }
};
class C : public A, public B { };
int main() {
C obj;
obj.showA();
obj.showB();
}
In the above example, C inherits from both A and B, making multiple inheritance
possible in C++. However, Java does not support multiple inheritance through
classes.
Why Java Does Not Support Multiple Inheritance?
Java does not allow multiple inheritance using classes due to the following
reasons:
1. Diamond Problem:
If two parent classes have the same method and a child class inherits from both,
the compiler will be confused about which method to use.
This creates ambiguity, which Java avoids by disallowing multiple inheritance.
Example:
class A {
void show() { System.out.println("Class A"); }
}
class B {
void show() { System.out.println("Class B"); }
}
// class C extends A, B { } // Not allowed in Java
interface A {
void showA();
}
interface B {
void showB();
}
class C implements A, B {
public void showA() {
System.out.println("Class A method");
}
public void showB() {
System.out.println("Class B method");
}
}
public class Main {
public static void main(String[] args) {
C obj = new C();
obj.showA();
obj.showB();
}
}
OUTPUT
Conclusion
Java does not support multiple inheritance through classes due to complexity,
ambiguity (diamond problem), and maintenance challenges. However, Java
allows multiple inheritance through interfaces, which provide a clean, structured,
and conflict-free approach. Thus, interfaces serve as a powerful alternative to
multiple inheritance in Java.
Plagiarism Report