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