【问题标题】:Difference between object created with new keyword and this keyword [duplicate]使用 new 关键字和 this 关键字创建的对象之间的区别 [重复]
【发布时间】:2019-01-17 03:02:47
【问题描述】:

我对 java 对象的创建有疑问。下面的代码表示 new 关键字和 this 关键字创建的对象是相同的。但是为什么我们不能在main方法中使用this关键字调用其他类的非静态方法,但是我们可以使用new关键字的对象引用在main方法中调用其他类的方法。 输出与下面的代码相同,这意味着我认为两者创建的对象是相同的。

class A5 {
    void m() {
        System.out.println(this); //prints same reference ID
    }
    public static void main(String args[]) {
        A5 obj=new A5();
        System.out.println(obj); //prints the reference ID
        obj.m();
    }
}  
 output: A5@22b3ea59

A5@22b3ea59

【问题讨论】:

  • 您的问题是误解的结果:this 不创建对象,它只是对当前对象的引用。

标签: java object this-keyword


【解决方案1】:

此关键字不会创建新对象。 this 关键字引用类的当前实例。所以 A5 类下的 this 关键字代表 A5 的一个实例 -> 只能使用此关键字调用 A5 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-21
    相关资源
    最近更新 更多