In java, multiple inheritance is not supported because of ambiguity problem. We can take the below example where we have two classes Class1 and Class2 which have same method display(). If multiple inheritance is possible than Test class can inherit data members (properties) and methods (behaviour) of both Class1 and Class2 classes. Now, Test class have two display() methods inherited from Class1 and Class2. Problem occurs in method call, when display() method will be called with Test class object which method will be called, will it be of Class1 or Class2. This is ambiguity problem because of which multiple inheritance is not supported in java.
Example:
class Class1{ public void display(){ System.out.println("Display method inside Class1."); } } class Class2{ public void display(){ System.out.println("Display method inside Class2."); } } //let multiple inheritance is possible. public class Test extends Class1, Class2{ public static void main(String args[]){ Test obj = new Test(); //Ambiguity problem in method call which class display() method will be called. obj.display(); } } |
Output:
Exception in thread "main" java.lang.Error: Unresolved compilation problem: at com.w3schools.business.Test.main(Test.java:19) |
Java interview questions on Inheritance
- Why multiple inheritance is not supported in java?
- How to implement multiple inheritance in java?
- Are interfaces also inherited from Object class?
- Why an interface cannot have constructor in java?
- How do you restrict a member of a class from inheriting to it’s sub classes?
- Can a class extend itself in java?
- Are constructors inherited in java?
- What happens if both superclass and subclass have a field with same name?
- Are static members inherited to subclasses in java?