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

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

问题描述

我一直在使用静态方法修饰符并且遇到了一种奇怪的行为。

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修饰符包含到静态方法中,则编译失败
ts()中的B不能覆盖A中的ts();重写方法是静态最终

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天全站免登陆