Behaviour of final static method

2019-01-04 07:06发布

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() {
    }
}

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?

7条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-01-04 07:32

static methods cannot be overriden

This is not exactly true. The example code really means that the method ts in B hides the method ts in A. So its not exactly overriding. Over on Javaranch there is a nice explanation.

查看更多
登录 后发表回答