【发布时间】: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