Override Private Final methods in Java

class X1
class X1
{
    private final void show() { ... }
}

class X2 extends X1
{
    private final void show() { ... }
}

Question 1

The code is compiling without any errors Because the final keyword prevents the method from being overwritten, why does the code compile?

Question 2

If I remove the private keyword from both show methods, the code will not compile as expected Why?

Solution

In X2, the method is not the same method, it hides the method in x1 Because the method in X1 is private, X2 does not know it, so it can reuse the method signature Therefore, when you have an x2 object and you call show, it will use the X2 program If you have an X1 object, it will use the X1 program

If you use the @ override annotation on X2, it will warn that the method to be overridden does not exist (or error, not 100% sure)

Signing in the same way is obviously not a good idea, because people who check it later may be very confused, and it certainly can't express your intention clearly

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>