Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/386.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 父类和实现接口中同名的静态和非静态方法_Java_Inheritance_Static Methods - Fatal编程技术网

Java 父类和实现接口中同名的静态和非静态方法

Java 父类和实现接口中同名的静态和非静态方法,java,inheritance,static-methods,Java,Inheritance,Static Methods,我不是在问接口和抽象类之间的区别 这是个人的成功,对吗 interface Inter { public void fun(); } abstract class Am { public static void fun() { System.out.println("Abc"); } } public class Ov extends Am implements Inter { public static void main(String[]

我不是在问接口和抽象类之间的区别

这是个人的成功,对吗

interface Inter {
    public void fun();
}

abstract class Am {
    public static void fun() {
        System.out.println("Abc");
    }
}

public class Ov extends Am implements Inter {
    public static void main(String[] args) {
        Am.fun();
    }
}

为什么会产生冲突?

一个
静态方法和非
静态方法不能在同一
类中具有相同的签名。这是因为您可以使用引用访问
静态
和非
静态
方法,编译器将无法确定您是要调用
静态
方法还是非
静态
方法

例如,考虑以下代码:

Ov ov = new Ov();
ov.fun(); //compiler doesn't know whether to call the static or the non static fun method.

Java允许使用引用调用
静态
方法的原因是允许开发人员无缝地将
静态
方法更改为非
静态
方法。

我们必须编写语法正确的代码。同样重要的是要理解我们的代码不会给编译器带来任何歧义。如果我们有任何这样的歧义,语言设计者已经注意到不允许编译这样的代码

类从其超类继承行为。只需使用类名,也可以从实例访问静态方法。假设有一个方法具有相同的名称和签名(除了
static
关键字),在实例上调用该方法将使编译器无所适从。它将如何决定程序员打算做什么,他或她打算调用哪两种方法?。因此,语言设计者决定让这种情况导致编译错误

依照

如果类C声明或继承了一个静态方法m,那么m被称为在C的超类和超接口中隐藏任何方法m',其中m的签名是m'签名的子签名(§8.4.2),否则C中的代码可以访问该方法。 如果静态方法隐藏实例方法,则是编译时错误。


问题是什么?静态方法可以使用实例调用。不。Java中的任何内容都不能使用实例调用。(至少程序员不这么认为)这不是100%正确:如果成员和静态方法遵守相同的重载规则,则它们可以有相同的名称,这意味着签名至少在参数类型上应该不同。@ceztko当然。我相信这意味着我们谈论的是同一个签名,而不仅仅是同一个名字;然而,编辑了答案以明确这一点。
public class Ov extends Am implements Inter {
    public static void main(String[] args) {
        Ov.fun(); //static method is intended to call, fun is allowed to be invoked from sub class.
        Ov obj = new Ov();

        obj.fun(); //** now this is ambiguity, static method can 
                   //be invoked using an instance, but as there is  
                 //an instance method also hence this line is ambiguous and hence this scenario results in compile time error.**
    }
}