1

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.

4
  • 3
    The reason you mark a method final in the first place is to stop it being overridden - that's exactly what it's designed to do. Commented Mar 4, 2015 at 15:30
  • final is just designed for preventing the method to be overriden and as for private the derived class has no access to such methods. Commented Mar 4, 2015 at 15:34
  • @JonK i now that we cannot override private and final method but my professor said that we can make the same method with the same signature yet this is not overriding. and i do not understand this. Commented Mar 4, 2015 at 15:35
  • 1
    Overloading a method is creating a new method with a different signature. It's like asking why can I create two method which start with the same letter (in this case the signature starts with the same word) Commented Mar 4, 2015 at 17:07

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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"; } } } 

2 Comments

thanks for the excellent explanation appreciated can you please explain for me why static methods also cannot be overloaded and are they inherited??

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.