【发布时间】:2016-04-26 14:42:04
【问题描述】:
我对 static methods 和 java 中的对象创建有点困惑。
我们知道我们可以像这里一样在静态方法中访问静态成员。
public static void main(String[] args){
// only static method from outside ( without any object )
}
但我愚蠢的问题是,为什么 java 允许这样做?
`public static void main(String[] args){
Object o = new Object(); // is constructor implicitly static?
// I'm sure no but why java allow this to call here?
}
我知道上面的语句类似于在静态方法中声明局部变量。
public static void main(String[] args){
int a = 3;
}
但我对构造函数有点困惑。
【问题讨论】:
-
new运算符在调用该对象的构造函数之前创建对象。因此,构造函数在现有对象上执行,而不是在任何类上静态执行。 -
@AndreasFester 那么为什么大多数人说我们通过这个
new Object();调用构造函数@ -
但这就是我所说的 - 您可以将对象创建视为由
new执行的两步过程。请参阅@PeterLawrey 的答案。 -
@LetDoit 它被称为构造函数。
标签: java constructor