Sara Chatila
Sara Chatila

Reputation: 101

why we cannot override private and final methods?

Why we can make a method of same signature as a private method but we can not override it

I am no understanding why we cannot override a private method but we can make another method of same signature
I think that they are the same.

Upvotes: 1

Views: 847

Answers (2)

gtgaxiola
gtgaxiola

Reputation: 9331

Perhaps this can explain it

You have two classes StackOverflow and A that extends StackOverflow

You see how both classes have the same private String myStackOverflow() signature?

This method is independent on each class and it can not be accessed outside of their own class (thus the private keyword).

That is not the case with hello() which is public

Class A can see it (because is an extension of StackOverflow), and may (or may not) override it.

public class StackOverflow {

    public void hello() {
        System.out.println("Hello: " + myStackOverflow());
    }

    private String myStackOverflow() {
        return "Welcome to StackOverflow";
    }

    public class A extends StackOverflow{

        @Override
        public void hello() {
             System.out.println("Hi, how are you? " + myStackOverflow());
        }

        private String myStackOverflow() {
            return "I hope you like your stay on StackOverflow";
        }   
    }

}

Upvotes: 2

Hoopje
Hoopje

Reputation: 12932

The final keyword is meant to forbid anyone from overriding a method. You can mark a method as final if your class depends on the specific implementation of that method, to prevent other code from breaking your class.

A private method is only visible to the class to which it belongs. Therefore subclasses cannot override a private method: the subclass is not aware that a method of the same signature already exists in a superclass.

Upvotes: 4

Related Questions