Inheritance

Given the following two classes...

abstractpublicclass A{

public String element ="A";

void test(){

System.out.println("A's method: " + element);

}

}

and

publicclass Cextends A{

public String element ="C";

publicstaticvoid main(String[] args){

C c =new C();

c.test();

}

}

I get "A's method: A" as output

My question is, since C inherits the methodtest, why doesn't the program output the member "element" from C? And is there a way of using A's method with C's member variable?

[1316 byte] By [Raphael.Blancharda] at [2007-11-27 8:26:05]
# 1

> My question is, since C inherits the method

> test, why doesn't the program output the

> member "element" from C? And is there a way of using

> A's method with C's member variable?

No, but why is C declaring an attribute with the same name? Just assign a value to the A.element instead.

Kaj

kajbja at 2007-7-12 20:15:21 > top of Java-index,Java Essentials,Java Programming...
# 2

You shadow the variable element in C. That means that C isn't accessing the inherited version's, it's using it's own. Since the test method is only defined in the A class, it can't print C's version of the variable. Try giving C a constructor and setting element = "C"; without declaring it as a new variable.

public C() {

element = "C";

}

hunter9000a at 2007-7-12 20:15:21 > top of Java-index,Java Essentials,Java Programming...
# 3
Thanks.I get it now.
Raphael.Blancharda at 2007-7-12 20:15:21 > top of Java-index,Java Essentials,Java Programming...