简体   繁体   中英

public final or protected final method does not override in base class and when we make a method “PRIVATE FINAL” in parent class its override

public final or protected final method does not override in base class is simple and when we make a method private final in parent class it is overridden even if you make a parent class private final and extends this in child class with method protected final it overrides. Can someone explain this behaviour?

class A {

    private final void show() {
        System.out.println("Show method from A");
    }
}

class B extends A {

    protected final void show() {
        System.out.println("Show method from B");
    }

    public static void main(String... s) {
       new B.show();
    }
}

Hi as other people said you misunderstood about overriding. First of all the show method in class A is private. So private members are not accessible from out side of that class.The below example will explain that:

class A {
    private final void show() {
        System.out.println("Show method from A");
    }
}

public class B extends A {
    // protected final void show() {
    //     System.out.println("Show method from B");
    // }

    public static void main(String... s) {
        new B().show();
    }
}

If you compile this it will gives the below error:

B.java:12: error: cannot find symbol
        new B().show();
             ^
symbol:   method show()
location: class B
1 error

Here in your question it's calling the method "show()" which is defined in the class B not in Ai hope this will clarify your doubt.

You can declare some or all of a class's methods final. You use the final keyword in a method declaration to indicate that the method cannot be overridden by subclasses. The Object class does this—a number of its methods are final.

You might wish to make a method final if it has an implementation that should not be changed and it is critical to the consistent state of the object.

Statement From java official Documents .

If your code was

A a = new B();
a.show();

Then you would be attempting to call the method from the parent class which cannot be overridden. As that's private in your example, you'll not get it to work. Try it with the methods as public.

So what's happening is that your B.show() method is masking A.show() when the type of object is B - that's always the way things work. Overriding methods works when your reference is of a type of the parent class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM