简体   繁体   中英

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();
       }
 }
  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 eg 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....

Unlike c++, Overridden method is called even the call is made from super class constructor.

This is polymorphism. So you are running an instance iniatilizer in A which calls the print method. As the type is actually B it's the method against B which gets executed.

my question is how inside the super class constructor we are able to access the subclass method

I'm not sure I understood your question... But if you want to call method print() of A from B you can do it by using the "super" keyword.

class B extends A {
       B() { super.print(); }

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

       public static void main(String args[]) {
         new Stest();
       }
 }

this refers to object which calls the method. Hence it refers to the class B object. You can refer the link below:

http://www.cs.utexas.edu/~lavender/courses/tutorial/java-05.pdf

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM