SE450: Types: Multiple inheritance [31/47] Previous pageContentsNext page

Java 8 allows default implementations in interface.

There are restrictions to prevent issues caused by multiple inheritance in C++.

file:types/multipleInheritance1/Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package types.multipleInheritance1;

/* 
 * Uncommenting h or g below causes interface K to fail to compile
 * "The default method h() inherited from I2 conflicts with another method inherited from I1"
 * 
 * Uncommenting toString below causes I1 to fail to compile, with error:
 * "A default method cannot override a method from java.lang.Object"
 */
interface I1 { 
  public void f ();
  default public void g () { System.out.println ("I1.g"); }
  //public void h ();
  //default public String toString () { return "I1"; }
}
interface I2 {
  public void f ();
  //default public void g () { System.out.println ("I2.g"); }
  default public void h () { System.out.println ("I2.h"); }
}

interface K extends I1, I2 { }

class C implements K { 
  public void f () { System.out.println ("C.f"); } 
}
public class Main {
  public static void main (String[] args) {
    C x = new C ();
    x.f ();
    x.g ();
    x.h ();
  }
}

file:types/multipleInheritance2/Main.java [source] [doc-public] [doc-private]
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package types.multipleInheritance2;

/* 
 * The "diamond of death" is not a problem in java, since multiple inheritance
 * is only possible for interfaces, and interfaces use "virtual inheritance" and
 * does not allow interfaces to have fields (no multiple-inheritance of state)
 * 
 * See
 * http://stackoverflow.com/questions/137282/how-can-you-avoid-the-diamond-of-death-in-c-when-using-multiple-inheritance
 * http://docs.oracle.com/javase/tutorial/java/IandI/multipleinheritance.html
 */
interface I0 {
  public void f ();
}
interface I1 extends I0 { 
  default public void g () { System.out.println ("I1.g"); }
}
interface I2 extends I0 {
  default public void g () { System.out.println ("I2.g"); }
}

/* It is possible to inherit conflicting defaults, as long as you don't use them!
 * If you comment out the definition of g in C or K below, you will get an error!
 */
class C implements I1, I2 { 
  public void f () { System.out.println ("C.f"); } 
  public void g () { System.out.println ("C.g"); } 
}
interface K extends I1, I2 { 
  default public void g () { System.out.println ("I2.g"); }
}
public class Main {
  public static void main (String[] args) {
    C x = new C ();
    x.g ();
  }
}

Previous pageContentsNext page