java静态关键字
我知道 static 的定义,它是一个将变量或方法引用到类本身的关键字。这是否意味着如果我在一个名为 calculator
的类中编写一个名为 parseInt()
的方法,并在另一个名为 parseInt()
的类中编写另一个名为 parseInt()
的方法mathProgram
,编译器 Eclipse 会知道方法 parseInt()
引用的是哪个类?
I know the definition of static which is a keyword to refer a variable or method to the class itself. Could this mean if I wrote a method called parseInt()
in a class called calculator
and another method called parseInt()
in a different class called mathProgram
, the compiler Eclipse will know which class the method parseInt()
is referring to?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要通过引用它所属的类来调用静态方法:
与 不同 因此
以这种方式编写,JVM 很清楚您所引用的是哪个方法。
编辑:您还可以使用实例变量调用静态方法,但这种形式很糟糕,应该避免。请参阅 这个 SO 答案以获取更多信息。
编辑2:这是Java编码的链接关于从实例变量调用静态方法的约定部分。 (感谢Ray Toal提供了此处发布的问题)
You need to call static methods by referencing the class it is a part of:
Is not the same as
So written this way it is clear to the JVM which method you were referring to.
Edit: You can also call static methods using an instance variable but this is in bad form and should be avoided. See this SO answer for more info.
Edit2: Here's a link to the Java Coding Conventions section regarding the use of calling static methods from instance variables. (Thanks to Ray Toal for the link left in the answer to a question posted here)
是的,因为静态方法和变量必须位于类中,并且要在该类之外调用它们,您需要限定它们。
例如Calculator.parseInt()和OtherClass.parseInt()。
Eclipse 使用它来区分它们。
Yes, because static methods and variables must be in a class and to call them outside of that class you need to qualify them.
For example
Calculator.parseInt()
andOtherClass.parseInt()
.Eclipse uses that to tell them apart.
如果该方法是静态的,则需要使用类名来调用它:
否则,使用实例来调用它:
无论哪种方式,它都明确是您想要的。
If the method is static, you need to call it using the classname:
Otherwise, with an instance:
Either way, its explicit which you want.