为什么Java静态方法可以调用构造函数,但不能引用它呢? [英] Why can a Java static method call a constructor, but not refer to this?
问题描述
我的假设:
- 静态方法不能调用非静态方法.
- 构造函数是一种方法,没有返回类型.
- Static method cannot cannot call non-static methods.
- Constructors are kind of a method with no return type.
给出此示例...
public class Main {
public static void main(String[] args) {
Main p = new Main(); // constructor call
k(); // [implicit] `this` reference
}
protected Main() {
System.out.print("1234");
}
protected void k() {
}
}
- 此行打印1234:
Main p = new Main()
- 此行引发异常:
k()
示例代码为什么要做这两件事?他们不与我的上述假设相抵触吗?我的假设正确吗?
推荐答案
1-静态方法不能调用非静态方法.
1 - Static method cannot cannot call non-static methods.
可以,但是需要一个对象来调用该方法.
在静态方法中,没有可用的 this
引用,因此, foo()
(等效于 this.foo()
)是非法的.
In a static method, there's no this
reference available, so foo()
(which is equivalent to this.foo()
) is illegal.
2-构造函数是一种没有返回类型的方法.
2 - Constructors are kind of a method with no return type.
如果应该将它们与方法相比 会说构造函数更接近于非静态方法(因为在构造函数中确实存在 this
引用).
If they should be compared to methods, I would say constructors are closer to non-static methods (since there is indeed a this
reference inside a constructor).
鉴于此观点,您应该清楚为什么静态方法可以毫无问题地调用构造函数.
Given this view, it should be clear to you why a static method can call a constructor without any problems.
所以,总结一下:
Main p = new Main();
可以,因为 new Main()
不依赖任何现有对象.
is okay, since new Main()
does not rely on any existing object.
k();
不好,因为它等同于 this.k()
,并且 this
在您的(静态)主方法中不可用.
is not okay since it is equivalent to this.k()
and this
is not available in your (static) main method.
这篇关于为什么Java静态方法可以调用构造函数,但不能引用它呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!