Java 爪哇语;新";静态法中的算子
我知道这是一个引用变量,当类加载器第一次访问类时,它保存对象和静态方法加载的引用,以创建实例,或访问静态方法或字段。 为什么不允许Java 爪哇语;新";静态法中的算子,java,static,new-operator,Java,Static,New Operator,我知道这是一个引用变量,当类加载器第一次访问类时,它保存对象和静态方法加载的引用,以创建实例,或访问静态方法或字段。 为什么不允许这个而允许它本身呢?例如 Class A{ public static void main(String... args){ this.method(); //not allowed new A().method(); //allowed, how? } void method(){ System.out.prin
这个
而允许它本身呢?例如
Class A{
public static void main(String... args){
this.method(); //not allowed
new A().method(); //allowed, how?
}
void method(){
System.out.println("Class A");
}
}
您在静态上下文中没有实例this
,因此无法调用该方法
new A().method(); //allowed, how?
您拥有由new
操作符创建的实例,以便可以调用方法
要在没有实际实例的情况下调用方法,必须将其声明为静态。i、 e:
static void method(){
System.out.println(“Class A”);
}
仅调用method()
并通过实例执行此操作:
public class A {
public static void main(String[] argv) {
method(); //works because method is static
new A().method(); //still ok, we can call static method using an instance
this.method(); //not allowed, there is no 'this' in static context
}
static void method(){
System.out.println("Class A");
}
}
static
变量和实例变量遵循您在声明中初始化时提到的初始化顺序。静态初始值设定项块也遵循该顺序
另一方面,方法(包括构造函数)在运行时不需要初始化。它们在编译时被完全定义,因此存在,并且可以在类加载时调用,也可以在初始化完成之前调用。因此,main
方法实例化类(调用默认构造函数)并调用稍后声明的方法没有问题,因为method
在main
下面声明
此外,
main
方法也仅在任何静态初始化完成后执行。在静态上下文中没有此
。静态上下文独立于任何类实例而存在newa().method()
正在创建一个新实例,并在此基础上调用该方法。“此时静态方法在编译时加载未知对象的状态”这是一个令人困惑的描述,并向我表明您对static
的实际含义理解不足。我建议你重温一些教程。那里已经有大量的信息,我们不会为您重复。此
引用实际实例<代码>静态表示它是类的成员(字段、方法等),而不是来自/an实例<上面的code>main是static
,因此它是类的一个方法,因此没有实例被认为是此
<另一方面,code>newa()正在创建(并返回)一个实例,因此可以调用(访问)它的方法。编译时没有加载任何内容。。。正如Michael所写,检查static
的确切含义这就是类和对象之间的区别所在(一个类可以创建0个、1个或多个对象)。当执行main
时,类被完全初始化,因此此时(在main
内部)在创建和使用对象时没有问题。“当类加载器首次访问该类时加载静态方法”听起来不正确。“静态方法加载”是什么意思?您的意思是在类加载时执行它吗?如果是,你怎么会这样认为?假设您有一个带有静态方法的类,比如class Foo{public static void saticMethod(){System.out.println(“executing staticMethod()”;}}}
,当您第一次将它与new Foo()
一起使用时,您会看到executing staticMethod()
?不。看起来你误解了什么是static
。请阅读。
public class A {
public static void main(String[] argv) {
method(); //works because method is static
new A().method(); //still ok, we can call static method using an instance
this.method(); //not allowed, there is no 'this' in static context
}
static void method(){
System.out.println("Class A");
}
}