top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

Does Java have Multiple Inheritance if yes give an example if no then explain it?

+1 vote
49 views
Does Java have Multiple Inheritance if yes give an example if no then explain it?
posted Jun 28, 2017 by Ajay Kumar

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button

1 Answer

0 votes

No Java does not support the multiple inheritance -

Reason of the diamond issue arises because of multiple inheritance, consider the following example

// A Grand parent class
class GrandParent
{
    void fun()
    {
        System.out.println("Grandparent");
    }
}

// First Parent class
class Parent1 extends GrandParent
{
    void fun()
    {
        System.out.println("Parent1");
    }
}

// Second Parent Class
class Parent2 extends GrandParent
{
    void fun()
    {
        System.out.println("Parent2");
    }
}

// Error : Test is inheriting from multiple classes
class Test extends Parent1, Parent2
{
   public static void main(String args[])
   {
       Test t = new Test();
       t.fun();
   }
} 

On calling the method t.fun() will cause complications such as whether to call Parent1’s fun() or Beta’s fun() method. Therefore, in order to avoid such complications Java does not support multiple inheritance of classes.

answer Jun 28, 2017 by Salil Agrawal
But interface have multiple inheritance. Multiple inheritance also part of java. when we need multiple inheritance then we use interface. this is advantage of interface.
package multiple_inheritance;
public class Multiple_inheritance {

    public static void main(String[] args) {
        System.out.println("Vehicle");
        Vehicle obj = new Vehicle();
        obj.distance();
        obj.speed();
        // TODO code application logic here
    }
    
}
interface vehicleone{
    int  speed=90;
    public void distance();
}

interface vehicletwo{
    int distance=100;
    public void speed();
}

class Vehicle  implements vehicleone,vehicletwo{
    public void distance(){
        int  distance=speed*100;
        System.out.println("distance travelled is "+distance);
    }
    public void speed(){
                System.out.println("speed is "+speed);
    }
}
Yes Ajay that's correct. Interfaces can have multiple inheritance and to avoid the conflict user or compiler has to decide which one to call.
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...