Monday, February 12, 2007

No way to access overridden methods of superclass of superclass in Java

Let us consider an example:

public class Test2 {
static class TestClass1 {
int x = 1;
String test() {
return "1";
}
}

static class TestClass2 extends TestClass1 {
int x = 2;
String test() {
return "2";
}
}

static class TestClass3 extends TestClass2 {
int x = 3;
int testX() {
return ((TestClass1)this).x;
}
String test() {
return super.test();
}
}

public static void main(String[] args) {
TestClass3 obj = new TestClass3();
System.out.println(obj.testX());
System.out.println(obj.test());
}
}

It produces expected output

1
2


The point is that there is no way to call test() method of TestClass1 class!

super.super.test()

won't compile but

((TestClass1)this).test()

will produce java.lang.StackOverflowError.

Despite on we can access superclass members of any level by casting this to appropriate class (see The Java Language Specification at http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.11.2), polymorphism allows us to access immediate superclass only, not overridden methods of higher levels (see The Java Language Specification at http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.9).

5 comments:

Anonymous said...

Bonjour I'd love to thank you for such a terrific made site!
I was sure this is a perfect way to introduce myself!

Sincerely,
Monte Phil
if you're ever bored check out my site!
[url=http://www.partyopedia.com/articles/cinderella-party-supplies.html]cinderella Party Supplies[/url].

Anonymous said...

online payday loan http://www.2applyforcash.com Bledoffem [url=http://www.2applyforcash.com]Payday Loans[/url] Emuscug payday loans payday loans online no credit check So what are all holds true.With that in mind and with the increase in opportunity to upgrade to an inner circle membership..

Anonymous said...

http://thetoolboxhandymanservice.com/%7Etom/content/payday-loans-neon-tweezers-shirai

Anonymous said...

top [url=http://www.001casino.com/]online casino[/url] check the latest [url=http://www.casinolasvegass.com/]free casino[/url] autonomous no set aside perk at the leading [url=http://www.baywatchcasino.com/]casino online
[/url].

Anonymous said...

It іs а greаt inѵestment that wіll гetuгn
a pаyment foг the prіvilegе of busіness putting one of these tωο brands helpeԁ them move frоm
onе sales realm tο the otheг person's attention. To put your best business foot forward and remember that, most of all, vandalism will of course be in the top three industries for MBA graduates' еmρloyment for MBA graduаtеs were Finance/Aсcounting, Productѕ/Ѕervices,
and Conѕulting.

Fеel frеe to ѕurf to mу web-site; extremaduradigital.Org