Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

questions about this reference in Java

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

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

1 Reply

0 votes
by (71.8m points)
  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....

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...