java-ee - Java this关键字疑问
PHPz
PHPz 2017-04-18 10:32:07
0
5
468
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指向谁?

PHPz
PHPz

学习是最好的投资!

reply all(5)
Peter_Zhu

In Java, the this keyword does not point to the current object?

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:

NewDemo a =new NewDemo ();

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.

Ty80

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方法,所以完全可以调用printMethod. The subject can learn more about the concepts of polymorphism and inheritance, and savor them carefully.

Ty80

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template