Artem's blog

March 24, 2008

How to access overridden methods of superclass of a superclass in Java?

Filed under: Software — Tags: , , , , , , — Artem @ 3:42 AM

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 the TestClass1 class!

super.super.test()

won’t compile but

((TestClass1)this).test()

will produce java.lang.StackOverflowError.

Despite that 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).

 

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URL

Leave a comment

 

You need to log in to vote

The blog owner requires users to be logged in to be able to vote for this post.

Alternatively, if you do not have an account yet you can create one here.

Powered by Vote It Up

Powered by WordPress