java - 抽象类的静态方法和抽象方法为什么不能同名同参?
PHP中文网
PHP中文网 2017-04-17 18:00:38
0
5
617
public abstract class Test {

    public static void test(){

    }

    public abstract void test();

}

我觉得这样可以的啊~~为什么编译失败。

PHP中文网
PHP中文网

认证0级讲师

reply all(5)
伊谢尔伦

This is because the signatures of static methods and instance methods cannot be the same, because Java allows calling class static methods on instance objects. It is precisely because of this permission that methods with the same signature cannot be used. See example:

public class Test {

    // public void main(String[] args) {} // Error

    public static void main(String[] args) {
        Test.hello(); // OK
        new Test().hello(); // OK
    }

    public static void hello() {
        System.out.println("hi");
    }
}
阿神

So who do you think jvm should execute?
Even if they are all normal methods, they cannot use the same name and the same parameters. The jvm will be stupid

左手右手慢动作

Method signature: The uniqueness of the method is determined by method name and parameter data type

The method names and parameters of the above two methods are consistent, resulting in an error during the compilation process

TestMethod.java:6: Error: Method test() is already defined in class TestMethod

public void test(){
            ^ 1 个错误
This is related to Java’s

dynamic bindingfeature

刘奇

Both static and abstract methods are defined by classes. Since they are all defined by classes, they must not have the same name and the same parameters.

刘奇

Overloading and rewriting in Java do not allow such rules.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template