public abstract class Demo{
public Demo(){
this.print();
}
public abstract void print();
}
public class NewDemo extends Demo{
public NewDemo (){
this.print();
}
@Override
public void print() {
System.out.println("NewDemo");
}
}
public class Test{
public static void main(String args[]){
NewDemo a =new NewDemo ();
}
}
Java中this关键字不是指向当前对象。为啥在Demo构造器中能调用子类的print()方法?
抽象类的中的this指向谁?
Yes.
However, you need to instantiate to get the object. And you cannot instantiate an abstract class, only its non-abstract subclasses. For example, in your code:
At this time this is pointing to the object a.
this in the Demo class refers to the reference of the object obtained by instantiating it.
It is recommended that the subject understand the basic concepts of Java first.
Isn’t this pointing to the object at the time of instantiation? In addition, isn't NewDemo called in your Test? Demo is an abstract class that does not provide calls, right?
this
就是指当前对象,这个毋庸置疑,Demo
类中的this
其实是继承Demo的普通类
的实例对象,因为抽象类是不能实例化的,而这个继承Demo的普通类
必须要实现print
方法,所以完全可以调用print
Method. The subject can learn more about the concepts of polymorphism and inheritance, and savor them carefully.You can take out the bytecode to see which ones are dynamic and which ones are static.
this represents the current object. If you don’t like this, you can remove this