search

Home  >  Q&A  >  body text

java - 抽象类的静态方法和抽象方法为什么不能同名同参?

public abstract class Test {

    public static void test(){

    }

    public abstract void test();

}

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

PHP中文网PHP中文网2889 days ago620

reply all(5)I'll reply

  • 伊谢尔伦

    伊谢尔伦2017-04-17 18:02:38

    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");
        }
    }

    reply
    0
  • 阿神

    阿神2017-04-17 18:02:38

    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

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 18:02:38

    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

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 18:02:38

    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.

    reply
    0
  • 怪我咯

    怪我咯2017-04-17 18:02:38

    Overloading and rewriting in Java do not allow such rules.

    reply
    0
  • Cancelreply