Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a small doubt about this reference in the following program,why the result is "I am in B",my question is how inside the super class constructor we are able to access the subclass method.

 class A {

      A()
      {this.print();}

      public void print(){    
        System.out.println("I am in class A");
      }
}

class B extends A {

       public void print() {
         System.out.println("I am in class B");
       }

       public static void main(String args[]) {
         new Stest();
       }
 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
216 views
Welcome To Ask or Share your Answers For Others

1 Answer

  1. You get "I am in B" because of runtime polymorphism or in java terms the print() method in B overrides the print() method in A.
  2. Ideally you should never call non-private methods of non-final classes from base class constructor. For e.g. in your case, the print() of B gets called from A's constructor but B is not yet initialized, which in your case is fine, but if it used uninitialized fields then....

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...