下面的代码是如何工作的
目前我正在尝试像这样调用它:
class Test {
public static void test() {
System.out.println("hi");
}
public static void main(String[] args) {
Test t = null;
t.test();
}
}
代码的输出是 hi
Currently I'm trying to invoke it like this:
class Test {
public static void test() {
System.out.println("hi");
}
public static void main(String[] args) {
Test t = null;
t.test();
}
}
The output of the code is hi
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
尝试在点之前使用类名的
Test.test()
。静态方法是在类本身而不是类的实例上调用的。
Try
Test.test()
with the class name before the dot.Static methods are called on the class itself not instances of the class.
您不需要实例化 Test 来调用静态方法。你的主要可能是这样的:
You don't need to instantiate Test for calling a static method. Your main could be look like this:
静态方法应该使用类名来调用,而不需要创建类的实例,如
或
您也可以使用对象引用来引用静态方法,例如,
但不鼓励这样做,因为它没有明确说明它们是类方法。
所以在你的情况下:
或者
从 main 方法就可以了。
Static methiods should be invoked with the class name, without the need for creating an instance of the class, as in
or
You can also refer to static methods with an object reference like
but this is discouraged because it does not make it clear that they are class methods.
So in your case:
or
from the main method will do.
尝试:
Try:
你们在同一个类中,只需从
main()
调用test()
即可。You are in the same class, you can simply call
test()
frommain()
.只是为了lulz
just for lulz
静态方法和静态变量的好处是您不需要类的实例即可使用它们。
通常你会创建一个实例并调用该方法
但是对于静态方法第一行不是必需的,你只需要在开头写下类名
但是,在静态方法中你无法访问测试类中的任何实例变量- 除非它们也是静态的!
The good thing about static methods and static variables is that you do not need an instance of the class to use it.
Normally you would create an instance and call the method
However with static methods the first line is not necessary, You just need to write the Class name at the start
However, in static methods you are not able to access any instance variables inside the Test class - unless they are also static!
顺便一提。该代码工作正常,没有任何 nullpointerexception
此代码打印 hi
我想知道当使用引用调用静态方法时内部会发生什么。
By the way. The code works fine without any nullpointerexception
This code prints hi
I wanted to know what happens internally when a reference is used to invoke a static method.
它之所以有效,是因为当使用引用调用静态方法时,该引用未使用。编译器查看调用该方法的表达式的声明/静态/编译时类型,并使用该类型来查找静态方法。
对变量调用静态方法不会带来任何好处,而且可能会让那些认为发生了多态调用的人感到困惑。
It works because when invoking a static method using a reference, the reference is not used. The compiler looks at the declared/static/compile-time type of the expression the method is being called on, and uses that type to find the static method.
You gain nothing by calling a static method on a variable, and you can confuse people who think a polymorphic call is occurring.
调用
Test.test()
。由于main
方法是静态并且位于同一个类中,因此您也可以直接调用test()
。Call
Test.test()
. As themain
method is static and in the same class so you can also directly calltest()
too.