I have a class which has a method whose access specifier by default is public. Now, I would like to extend this class in a subclass and I want to override this method to hav
If this were allowed, there would be a backdoor through which you could call methods that should not be accessible.
Lets say that this is allowed
class Super {
public void method() {
System.out.println("Super");
}
}
class Sub extends Super {
// This is not allowed, but suppose it was allowed
protected void method() {
System.out.println("Sub");
}
}
// In another class, in another package:
Super obj = new Sub();
obj.method();
obj.method
would be possible, because method()
is public
in class Super. But it should not be allowed,
because obj is really referring to an instance of Sub, and in that class, the method is protected!
To restrict a call to a method in class Sub that should not be accessible from the outside, this restriction is put.
The short answer is that it is not allowed because it would break type substitutability; see also the Liskov Substititution Principle (LSP).
The point is that polymorphism in Java (and other programming languages) relies on you being able to treat an instance of a subclass as if it was an instance of the superclass. But if the method is restricted in the subclass, you find that the compiler cannot figure out whether the access rules allow a method to be called ...
For instance, lets assume that your example code was legal:
// Assume this code is in some other class ...
SuperClass s1 = new SuperClass();
s1.foo(); // OK!
SuperClass s2 = new Subclass();
s2.foo(); // What happens now?
SuperClass s3 = OtherClass.someMethod();
s3.foo(); // What happens now?
If you base the decision on whether s2.foo()
is allowed on the declared type of s2
, then you allow a call to a private
method from outside the abstraction boundary of Subclass
.
If you base the decision on the actual type of the object that s2
refers to, you cannot do the access check statically. The s3
case makes this even clearer. The compiler has absolutely no way of knowing what the actual type of the object returned by someMethod
will be.
Access checks that could result in runtime exceptions would be a major source of bugs in Java application. The language restriction under discussion here avoids this nasty problem.