on 1 comment

Multiple Inheritance in Java

Multiple inheritance is a concept of object oriented programming. In multiple inheritance, a class inherits the properties of two or more class. But java does not support multiple inheritance because of some issues. When both parent classes overrides the same method and child class object is calling that method, then compiler does not know which class method is to be called and which class to give high priority.
Multiple Inheritance
Multiple Inheritance

It will show error because one class trying to extending two classes.

// First Parent class
class ParentClass1
{
    void show()
    {
        System.out.println("ParentClass1");
    }
}
 
// Second Parent Class
class ParentClass2
{
    void show()
    {
        System.out.println("ParentClass2");
    }
}
class SubClass extends ParentClass1, ParentClass2{
 public static void main(String[] args) {
  SubClass obj = new SubClass();

  obj.show();
 }
}

Output:

SubClass.java:18: error: '{' expected
class SubClass extends ParentClass1, ParentClass2{
                                   ^
1 error

Multiple Inheritance by Interfaces

In java, one class can implements two or interfaces. This also does not cause any ambiguity because all methods declared in interfaces are implemented in class.

Example:

interface Interface1
{
   public void show();
}
interface Interface2
{
   public void show();
}
class SubClass implements Interface1, Interface2
{
   public void show()
   {
       System.out.println("A class can implements more than one interfaces");
   }
   public static void main(String args[]){
    SubClass obj = new SubClass();
    obj.show();
   }
}

Output:

A class can implements more than one interfaces


1 comment: