java 静态方法调用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2629475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Static method invocation
提问by user315459
Can we call a static method without mentioning the class name in Java?
我们可以在Java中不提类名的情况下调用静态方法吗?
回答by Brian Agnew
Yes you can. Check out static imports. You have to mention the class name in the importstatement, but after that you don't have to.e.g. from the linked article:
是的你可以。查看静态导入。你必须在import声明中提到类名,但之后你不必从链接的文章中提到:
import static java.lang.Math.abs;
import static java.lang.Math.max;
int xDist = abs(destination.getX() - x);
int yDist = abs(destination.getY() - y);
return max(xDist, yDist);
Introduced in Java 5.
在 Java 5 中引入。
回答by polygenelubricants
Yes, you can call a staticmethod without mentioning the class name. There's the import static(see JLS 7.5.4for exact mechanism), but even without it, if the name can be resolved (see JLS 15.12.1for exact mechanism) without fully qualifying the class, it will work.
是的,您可以在static不提及类名的情况下调用方法。有import static(有关确切机制,请参阅JLS 7.5.4),但即使没有它,如果可以在不完全限定类的情况下解析名称(有关确切机制,请参阅JLS 15.12.1),它将起作用。
The following code compiles and prints "Hello world!"as expected.
以下代码"Hello world!"按预期编译和打印。
import static java.lang.System.out;
public class Test {
static String greeting() {
return "Hello world!";
}
public static void main(String[] args) {
out.println(greeting());
}
}
outin the printlnstatement is actually a staticfield access of the class java.lang.System, not a staticmethod, but it's a staticmember access nonetheless. greeting()is a staticmethod invocation, and the class name can be omitted since its reference can be resolved without fully qualifying the name.
out在println语句中实际上是static类的字段访问java.lang.System,而不是static方法,但它static仍然是成员访问。greeting()是一个static方法调用,类名可以省略,因为它的引用可以在不完全限定名称的情况下解析。
Now let's ask if this is a good idea. Unless you're calling a staticmethod from within its class, IT'S NOT a good idea generally to omit the class name!!!
现在让我们问一下这是否是一个好主意。除非您static从其类中调用方法,否则通常省略类名不是一个好主意!!!
Let's focus on static importfirst. A quote from the guide:
让我们static import首先关注。来自指南的引用:
So when should you use static import? Very sparingly!Only use it when you'd otherwise be tempted to declare local copies of constants, or to abuse inheritance (the Constant Interface Antipattern). In other words, use it when you require frequent access to static members from one or two classes. If you overuse the static import feature, it can make your program unreadable and unmaintainable, polluting its namespace with all the
staticmembers you import. Readers of your code (including you, a few months after you wrote it) will not know which class a static member comes from. Importing allof the static members from a class can be particularly harmful to readability; if you need only one or two members, import them individually. Used appropriately, static import can make your program morereadable, by removing the boilerplate of repetition of class names.
那么什么时候应该使用静态导入呢?非常节俭!仅当您试图声明常量的本地副本或滥用继承(常量接口反模式)时才使用它。换句话说,当您需要频繁访问一两个类的静态成员时使用它。如果您过度使用静态导入功能,它会使您的程序不可读和不可维护,
static您导入的所有成员都会污染其命名空间。你的代码的读者(包括你,在你编写它几个月后)不会知道静态成员来自哪个类。全部导入类中的静态成员可能对可读性特别有害;如果您只需要一两个成员,请单独导入它们。如果使用得当,静态导入可以通过删除类名重复的样板文件使您的程序更具可读性。
The case is made stronger by the following example:
以下示例使案例更加强大:
class Base {
void task1() {
System.out.println("Base.task1");
}
static void task2() {
System.out.println("Base.task2");
}
}
class Child extends Base {
void task1() {
System.out.println("Child.task1");
}
static void task2() {
System.out.println("Child.task2");
}
}
//....
Base sweetChildOMine = new Child();
sweetChildOMine.task1(); // prints "Child.task1"
sweetChildOMine.task2(); // prints "Base.task2"
What a surprise! You'd think that since sweetChildOMinehas a reference to an instance of Child, sweetChildOMine.task2()should print "Child.task2"because it's overridden by Childclass, right?
多么惊喜!您会认为,既然sweetChildOMine引用了 的实例Child,就sweetChildOMine.task2()应该打印,"Child.task2"因为它被Child类覆盖了,对吗?
WRONG! A staticmethod can not be overridden! It can only be hidden by a subclass! In fact, if you tried to do the right thing and add the @Overrideannotation to task2, it would not compile!
错误的!一个static方法不能被覆盖!它只能被子类隐藏!事实上,如果您尝试做正确的事情并将@Override注释添加到task2,它将无法编译!
From JLS 15.12.4.4 Locate method to invoke:
If the invocation mode is
static, no target reference is needed and overriding is not allowed. Method mof class Tis the one to be invoked.
如果调用模式是
static,则不需要目标引用并且不允许覆盖。类T 的方法m是要调用的方法。
In fact, this problem is covered in Java PuzzlersPuzzle 48: All I Get Is Static. The conclusion given at the end of the puzzle is this:
事实上,这个问题在Java PuzzlersPuzzle 48: All I Get Is Static 中有介绍。拼图最后给出的结论是:
In summary, qualify
staticmethods invocations with a class name, or don't qualify them at all if you're invoking them from within their own class, but never qualify them with an expression. Also, avoid hiding static methods. Together, these guidelines help eliminate the misleading appearance of overriding with dynamic dispatch for static methods.
总之,
static使用类名限定方法调用,或者如果您从它们自己的类中调用它们,则根本不限定它们,但永远不要使用表达式限定它们。另外,避免隐藏静态方法。总之,这些指南有助于消除静态方法的动态调度覆盖的误导性外观。
It is best to follow all these recommendations together, so:
最好同时遵循所有这些建议,因此:
- If you're calling a
staticmethod within its own class, don't qualify - Otherwise, qualify with the class name
- If you're doing this a lot within one class, consider
static importof that specific method- Try not to
static importall members with*
- Try not to
- Never qualify with an expression
- If you're doing this a lot within one class, consider
- Don't hide a
staticmethod; you can't@Overrideit, it'll only cause confusion
- 如果你
static在它自己的类中调用一个方法,不要限定 - 否则,用类名限定
- 如果您在一个班级中经常这样做,请考虑
static import该特定方法- 尽量不要对
static import所有成员*
- 尽量不要对
- 永远不要用表达式限定
- 如果您在一个班级中经常这样做,请考虑
- 不要隐藏
static方法;你不能这样@Override做,它只会引起混乱
See also:
也可以看看:
回答by Abimbola
Yes you can call a static method without the class name. For example, if you are calling it within another static method of the same class.
是的,您可以在没有类名的情况下调用静态方法。例如,如果您在同一类的另一个静态方法中调用它。
public class TestStatic{
公共类 TestStatic{
static void hello()
{
System.out.println("Hello World");
}
static void hello2()
{
hello();
System.out.println("Welcome to java");
}
public static void main(String[] args)
{
hello2();
}
}
}
回答by OscarRyz
Yes.
是的。
class CallStaticMethodTest {
public static void staticMethodOne() {
System.out.println("Static method one");
}
// Invoke from a non-static method
public void instanceMethodOne() {
staticMethodOne();// Calling static method without mentioning the class name
}
// Invoke from another static method:
public static void staticMethodTwo() {
staticMethodOne();
}
}
回答by GuruKulki
Yes, adding to Brian Agnew you can call static methods through an instance of that class type as well.
是的,除了 Brian Agnew,您还可以通过该类类型的实例调用静态方法。

