最终静态方法的行为 [英] Behaviour of final static method

查看:24
本文介绍了最终静态方法的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在玩带有静态方法的修饰符,遇到了一个奇怪的行为.

I have been playing around with modifiers with static method and came across a weird behaviour.

正如我们所知,静态方法不能被覆盖,因为它们与类而非实例相关联.

As we know, static methods cannot be overridden, as they are associated with class rather than instance.

所以如果我有下面的代码片段,它编译得很好

So if I have the below snippet, it compiles fine

//Snippet 1 - Compiles fine
public class A {
    static void ts() {
    }
}

class B extends A {
    static void ts() {
    }
}

但是如果我在类 A 的静态方法中包含 final 修饰符,那么编译就会失败B 中的 ts() 不能覆盖 A 中的 ts();被覆盖的方法是静态 final.

But if I include final modifier to static method in class A, then compilation fails ts() in B cannot override ts() in A; overridden method is static final.

当静态方法根本无法被覆盖时,为什么会发生这种情况?

Why is this happening when static method cannot be overridden at all?

推荐答案

静态方法不能被覆盖,但可以隐藏.B 的 ts() 方法不会覆盖(不受多态性影响)A 的 ts() ,但它将隐藏它.如果您在 B 中调用 ts()(不是 A.ts()B.ts() ... 只是 ts()),将调用 B 中的一个而不是 A.由于这不受多态性的影响,因此 A 中的调用 ts() 永远不会重定向到 B 中的那个.

Static methods cannot be overridden but they can be hidden. The ts() method of B is not overriding(not subject to polymorphism) the ts() of A but it will hide it. If you call ts() in B (NOT A.ts() or B.ts() ... just ts()), the one of B will be called and not A. Since this is not subjected to polymorphism, the call ts() in A will never be redirected to the one in B.

关键字 final 将禁止隐藏该方法.因此它们不能被隐藏,并且尝试这样做会导致编译器错误.

The keyword final will disable the method from being hidden. So they cannot be hidden and an attempt to do so will result in a compiler error.

希望这会有所帮助.

这篇关于最终静态方法的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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