繁体   English   中英

Java - 使用 class 实例引用 static 方法

[英]Java - Referring static method using that class instance

使用 class 实例使用 static 方法时究竟会发生什么? 在构建级别和运行时。

提前致谢。

更新:有两个类,class 一个有一个方法,第二个使用该方法,一段时间后该方法更改为 static。 运行时,我得到 IncompatibleClassChangeError。

If you call a static method from a class instance, it is identical to calling it in the standard static fashion (ie from the class name.) The compiler is smart enough to know to make the static call.

如果你的意思是

class Foo {
  static void bar() { ... }
}

public class Baz {
  public static void main(String... argv) {
    new Foo().bar();  // Use static method here via instance
  }
}

然后该实例将被完全忽略。

如果你通过反射来做,那么它也会被忽略。

如果底层方法是 static,则忽略指定的 obj 参数。 它可能是 null。

考虑这种情况......

Class XYZ{

public static void functionTest(){
 // Your code
}

public static void main(String args[]){
XYZ x = new XYZ();
//Here we can execute the method functionTest() in 2 ways.
x.functionTest();
XYZ.functionTest();
}
}

Every class will have something called Context of a class , which means all the static methods and static variables get memory allocated in RAM without creating an object of that class and we call that memory as Context of a class.

一个reference(x)包含两部分,一个是对象(instance)的实际地址,另一个是class的上下文地址。

当我们在上面的场景中调用 x.function() 时,首先它总是搜索 class 的上下文,如果找到它就会执行它,如果找不到它就会从 class 的实例中执行它。

因此,无论您以何种方式尝试执行 static 方法,它将始终从 class 的上下文中执行,而不是从 class 的实例中执行。

这就是为什么可以以两种方式调用 class 的 static 成员的原因。

并且通过从实例调用该方法,我们没有必要创建根本不需要的 object(不必要的内存分配)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM