Friday, February 26, 2016

Java : Why multiple inheritance not allowed in Java (Diamond Problem) and Solution

Why multiple inheritance not allowed in Java (Diamond Problem) and Solution 


Problem :

class A { 
int i; 
void msg() {
        System.out.println("From A");
    } 
}

class B { 
  int i;   
void msg() {
        System.out.println("From B");
    } 
}

class C extends A,B {         // suppose if this was possible
    public static void main(String[] args) { 

        super.msg();                 // which msg() method would be invoked?   

 }
}

Solution 1: Using interface’s reference
interface Moveable{
    default void run(){
        System.out.println("I am running, kid !!");
    }
}
  
interface Crawlable{
    default void run(){
        System.out.println("I am running, daddy !!");
    }
}
  
public class Animal implements Moveable, Crawlable {
    public static void main(String[] args)
    {
        Moveable.super.run(); 
         Crawlable.super.run();
    }
}
So solve above conflict, caller class must decide which run() method it want to invoke and then call using

 
Solution 2 : Using Tree pattern

public class Canine extends Animal{}
public class Dog extends Canine{}

Solution 3 : Creating Object Instances 

class mobile_phone { void call(){}}
class tablet {void big_screen(){} }

class phablet {
                mobile_phone m;
                tablet  t;

phablet(){
                m= new mobile_phone ();
                t=  new tablet  ();
}
test(){
m.call();
t.big_screen();
}

No comments:

Post a Comment