2 Replies Latest reply: Jul 16, 2011 1:47 PM by Kayaman RSS

    Why Following is not possible using Inheritance

      public abstract class X {

      public class Y extends X {

      public class Z extends X {

      public abstract class A {
           public abstract void a1( X x);
      // or
           public abstract X a2( ---);

      public class B extends A {
           public void a( Y y){


      public class C extends A {
           public Z a2( ---){
        • 1. Re: Why Following is not possible using Inheritance
          Because you can only override a method with exactly the same signature.
          class Parent {
            void foo(Object s) {}
            void foo(String s) {}
          When you call foo(something), it is determined at compile time which signature will be called. There are rules (http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.2) that determine which signature will be used. It comes down to the one that's the "most specific," which ends up being intuitive in most normal cases, but the rules themselves are not an easy read.

          So we call foo(something), the compiler decides that it will either be foo(Object) or foo(String), depending on the compile-time type of "something".
          Object o1 = new Object();
          String s1 = "abc";
          Object o2 = s1;
          Object o3 = "xyz";
          foo(o1); // foo(Object)
          foo(s1); // foo(String)
          foo(o2); // foo(Object)
          foo(o3); ;; foo(Object)
          This is determined at compile time, and does not change at runtime.

          So, now, if we're going to override a method--which means that it will be determined at runtime which class's version of that method is called--we can only override a method with the exact same signature.

          The compiler has already determined that, when runtime comes around, the method we invoke will have exactly the signature foo(Object), or else it has determined that the method will have exactly the signature foo(String). The only thing that's left to decide at runtime is if we invoke Parent's version of that method, or some subclasses version of a method with that exact signature.
          • 2. Re: Why Following is not possible using Inheritance
            Because it was defined that way in the JLS.

            But don't worry, you won't need to worry about overly complex inheritance like that.