当我尝试覆盖静态方法时,为什么编译器没有抱怨? [英] Why doesn't the compiler complain when I try to override a static method?

查看:133
本文介绍了当我尝试覆盖静态方法时,为什么编译器没有抱怨?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们不能在Java中覆盖静态方法,但有人可以解释下面的代码吗?

I know that we cannot override static methods in Java, but can someone explain the following code?

class A {
    public static void a() { 
        System.out.println("A.a()");
    }
}   

class B extends A {
    public static void a() {
        System.out.println("B.a()");
    }
}

我怎样才能覆盖方法 a()在类 B

How was I able to override method a() in class B?

推荐答案

你没有在这里覆盖任何东西。要自己查看,请尝试在中将 @Override 注释放在类之前> B 并且Java将抛出错误。

You didn't override anything here. To see for yourself, Try putting @Override annotation before public static void a() in class B and Java will throw an error.

您刚刚在类 B中定义了一个函数调用 a(),它与类中的函数 a()不同(无关系) code> A 。

You just defined a function in class B called a(), which is distinct (no relation whatsoever) from the function a() in class A.

但是因为 Ba()与父类中的函数同名,所以隐藏 Aa() [正如Eng指出的那样。福阿德。在运行时,编译器使用声明的引用的实际类来确定要运行的方法。例如,

But Because B.a() has the same name as a function in the parent class, it hides A.a() [As pointed by Eng. Fouad]. At runtime, the compiler uses the actual class of the declared reference to determine which method to run. For example,

B b = new B();
b.a() //prints B.a()

A a = (A)b;
a.a() //print A.a(). Uses the declared reference's class to find the method.

您无法在Java中覆盖静态方法。记住 static 方法和字段与类相关联,而不是与对象相关联。 (虽然,在某些语言中,如Smalltalk,这是可能的。)

You cannot override static methods in Java. Remember static methods and fields are associated with the class, not with the objects. (Although, in some languages like Smalltalk, this is possible).

我在这里找到了一些好的答案:为什么Java不允许覆盖静态方法?

I found some good answers here: Why doesn't Java allow overriding of static methods?

这篇关于当我尝试覆盖静态方法时,为什么编译器没有抱怨?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆