0

My book doesn't give the greatest explanation, and I want to understand why I can't have a private method in the subclass when I have the same method signature in the superclass. Except the method in the superclass would be public.

I tried googling this answer and all I could find was stuff on overriding private methods. However, I'm trying to override a public method with a private method.

Kacy Raye
  • 1,312
  • 1
  • 11
  • 14

3 Answers3

2

By making the derived method private you'd be changing the contract made by the super class, preventing any further subclasses from accessing the originally public method.

A function passed a parameter typed to be of the super class would not know in advance whether it's allowed to call the method or not. This would be bad.

Alnitak
  • 334,560
  • 70
  • 407
  • 495
1

If you could, then what? You'd have overridden a public method with a private one, that would make the super class method invisible. Code counting on having that method available would break. One of the ideas of OO (called the Liskov Substitution Principle) is that the program should be able to manipulate objects at a high level, without having to know the exact implementation class being used; objects of any subclass should be substitutable for objects of their superclass. Being able to invalidate super class methods would undermine this.

Community
  • 1
  • 1
Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
1

According to the Java Language Specification, section 8.4.8.3, one cannot weaken the access privilege of a method when overriding, specifically:

The access modifier (§6.6) of an overriding or hiding method must provide at least as much access as the overridden or hidden method, as follows:

If the overridden or hidden method is public, then the overriding or hiding method must be public; otherwise, a compile-time error occurs.

If the overridden or hidden method is protected, then the overriding or hiding method must be protected or public; otherwise, a compile-time error occurs.

If the overridden or hidden method has default (package) access, then the overriding or hiding method must not be private; otherwise, a compile-time error occurs.

This is done so if you have a superclass reference to the subclass object, then you can still call that method, no matter what class it is -- the superclass, or any subclass -- e.g.

Superclass obj = new Subclass();
obj.method();

It must still be public.

rgettman
  • 176,041
  • 30
  • 275
  • 357