search

Home  >  Q&A  >  body text

java-ee - Java this关键字疑问

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指向谁?

PHPzPHPz2906 days ago502

reply all(5)I'll reply

  • 天蓬老师

    天蓬老师2017-04-18 10:34:07

    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.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:34:07

    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?

    reply
    0
  • 怪我咯

    怪我咯2017-04-18 10:34:07

    this就是指当前对象,这个毋庸置疑,Demo类中的this其实是继承Demo的普通类的实例对象,因为抽象类是不能实例化的,而这个继承Demo的普通类必须要实现print方法,所以完全可以调用printMethod. The subject can learn more about the concepts of polymorphism and inheritance, and savor them carefully.

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:34:07

    You can take out the bytecode to see which ones are dynamic and which ones are static.

    reply
    0
  • 黄舟

    黄舟2017-04-18 10:34:07

    this represents the current object. If you don’t like this, you can remove this

    reply
    0
  • Cancelreply