简体   繁体   English

为什么不能使用签名相同的静态和非静态方法呢?

[英]Is there a reason why one can't have a static and a non-static method with identical signature?

I just realized the following does not compile: 我只是意识到以下内容无法编译:

class MyCoolClass {
    static void do(){..}
    void do(){..}
}

Is there a good reason why this is not allowed? 有充分的理由为什么不允许这样做? Maybe it would cause some problem that I'm currently missing? 也许会导致我目前缺少的某些问题?

The only problem I can see currently is that someone might try to call the static method and actually calls the non-static one. 我目前只能看到的唯一问题是,有人可能会尝试调用静态方法,而实际上是调用非静态方法。 But that sounds comparable with static methods on subclasses that hide each other, so I wouldn't consider that a "good" reason. 但这听起来可以与彼此隐藏的子类上的静态方法媲美,所以我不会认为这是“好的”理由。

If one considers the object a method is called on the 0th argument to that method it even would be quite normal overloading of the method. 如果认为该对象在该方法的第0个参数上调用了一个方法,那么它甚至是正常的方法重载。

In case you are wondering: I would like to have this because it would allow creating a shortcut for new MyCoolClass().do() as MyCoolClass.do() or with static import even as do() . 如果您想知道:我想拥有它,因为它允许为new MyCoolClass().do()作为MyCoolClass.do()或静态导入(甚至与do()创建快捷方式。

It's because the Java compiler uses the name of the method and the ordered list of parameter types to uniquely identify the method within the class. 这是因为Java编译器使用方法的名称和参数类型的有序列表来唯一地标识类中的方法。 static is a modifier flag and is not considered part of the unique identification. static是修饰符标志,不被视为唯一标识的一部分。 Unique identification is also important at runtime because the class file contains only those keys necessary to identify the method. 唯一标识在运行时也很重要,因为类文件仅包含标识该方法所需的那些键。 The class name where the method is, then the method name, then the parameter list. 方法所在的类名称,然后是方法名称,然后是参数列表。

https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html#jvms-5.4.3.3 https://docs.oracle.com/javase/specs/jvms/se7/html/jvms-5.html#jvms-5.4.3.3

I think this might be problematic to handle when you are creating an object. 我认为在创建对象时可能很难处理。 As you probably know, you can call a static function through object reference like: 您可能知道,可以通过对象引用调用静态函数,例如:

SomeClass s = new SomeClass();
s.do(); //can be static method, can be normal method

Of course, it's rare to call static method through object, but it's possible. 当然,很少有人通过对象调用静态方法,但是有可能。

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

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