Diamond Problem

interface A

{

void foo();

}

abstractclass B

{

publicvoid foo()

{

System.out.println("B");

}

}

class Cextends Bimplements A

{

publicvoid foo()

{

System.out.println("C");

}

}

class Demo

{

publicstaticvoid main(String args[])

{

A c =new C();

B b =new C();

b.foo();// prints C

c.foo();// prints C

}

}

If there were 2 interfaces that were implemented in a class, i would have not complained because none has its seperate implementation defined, so which path my class followed in the inheritence hierarchy doesnt actually matter to me, since both are equivalent.

But the case i m discussing here, one of my abstract class actually has the implementation for foo(), so now I do give heed to the path followed.

Moreover, the foo() implementation in my concrete class, actually overloads both foo()'s , since inheritence and abstract class reference call to foo both print C

so does java still not experience Diamond Problem, because path followed is actually still unknown?

[2215 byte] By [enterneoa] at [2007-11-27 10:14:00]
# 1

> > interface A

> {

> void foo();

> }

>

> abstract class B

> {

> public void foo()

> {

> System.out.println("B");

> }

> }

>

> class C extends B implements A

> {

> public void foo()

> {

> System.out.println("C");

> }

> }

>

>

> class Demo

> {

> public static void main(String args[])

> {

> A c = new C();

> B b = new C();

> b.foo();// prints C

> c.foo();// prints C

> }

> }

>

>

> If there were 2 interfaces that were implemented in a

> class, i would have not complained because none has

> its seperate implementation defined, so which path my

> class followed in the inheritence hierarchy doesnt

> actually matter to me, since both are equivalent.

>

> But the case i m discussing here, one of my abstract

> class actually has the implementation for foo(), so

> now I do give heed to the path followed.

>

> Moreover, the foo() implementation in my concrete

> class, actually overloads both foo()'s , since

> inheritence and abstract class reference call to foo

> both print C

The C class does not overload the foo() method, it overrides it.

>

> so does java still not experience Diamond Problem,

> because path followed is actually still unknown?

The path is not unknown; it is always the one for the actual instance that is being referenced. This is meant to be a "feature" of Java's polymorphism (all polymorphism?) - if your reference is of a type higher in the class hierarchy you do not need to know the runtime type of the instance; that instances method will be the one called at runtime.

jbisha at 2007-7-28 15:30:31 > top of Java-index,Java Essentials,New To Java...