为什么java中的静态方法不能隐藏实例方法


class TestOverriding {
    public static void main(String aga[]) {
        Test t = new Fest();
        t.tests();
    }
}
class Test {
    void tests() {
        System.out.println("Test class : tests");
    }
}
class Fest extends Test {   
    static void tests() {
        System.out.println("Fest class : tests");
    } 
}

测试类是超类和Fest是它的子类,因为我们知道静态方法不能被覆盖,即使这样我得到错误,如"静态方法不能隐藏实例方法在java中",有人可以解释这个,提前感谢。

术语重写通常用于对象,因为使用相同的父引用,您可以从给定的子对象调用不同的方法。通过这种方式,静态方法不能被重写,因为它们与引用类型相关联,而不是与对象类型相关联。

重写是如何发生的?你在基类中指定一个方法,并在子类中放置相同的签名,这将自动覆盖该方法。如果您注意到,静态方法也是继承的,也就是说,如果父类包含静态方法,那么它可以被子类引用使用。例如:

public class TestOverriding {
    public static void main(String aga[]) {
        Fest t = new Fest();
        t.tests(); <-- prints "Test class : tests"
    }
}
class Test {
    static void tests() {
        System.out.println("Test class : tests");
    }
}
class Fest extends Test {   
    void tests3() {
        System.out.println("Fest class : tests");
    } 
}

现在,一个静态方法已经来到你的子类,你正试图在子类中定义一个具有相同签名的新方法。这就是问题的根源。如果您在单个类中执行此操作,则错误消息将不同。

案例1:相同的类

class Fest{   
    void tests3() {
        System.out.println("Fest class : tests3");
    } 
    static void tests3() {
        System.out.println("Fest class : static tests3"); <-- gives "method tests3() is already defined in class Fest"
    }
}

案例2:子类(static to instance)

class Test {
    static void tests() {
        System.out.println("Test class : tests");
    }
}
class Fest extends Test {   
    void tests() { <-- gives "overridden method is static"
        System.out.println("Fest class : tests");
    }
}

案例2:子类(instance to static)

class Test {
    oid tests() {
        System.out.println("Test class : tests");
    }
}
class Fest extends Test {   
    static void tests() { <-- gives "overriding method is static"
        System.out.println("Fest class : tests");
    }
}

对于静态方法使用与超类中的实例方法相同的方法名将是不好的做法,因为它非常令人困惑。

我想说,编译器很可能会保护您免受意外错误的侵害,因为它可能假设您确实想要覆盖该方法。

在这种情况下,像Fest t = new Fest(); t.tests()这样的东西太令人困惑了:它是什么意思?调用继承的实例方法Test.test ?还是调用Fest的静态方法

ClassA{
   public void disp(){}
//Error ,We can not define two members with same name (Note this till next step)
  //public static void disp(){}
}
ClassB extends ClassA{
//Now ClassB has one method disp() inherited from ClassA.
//Now declaring a static method with same 
//Error, as mentioned ClassB already has disp() and one more member with same //name is not allowed.
  //public static void disp(){}
}

最新更新