A quick example
class A {
protected int foo(int x){
return x;
}
}
class B extends A {
public int foo(int x){
return x*x;
}
}
This is allowed in Java and works without any issue. But let's say in another package you declare
A b = new B();
int z = b.foo(5);
Then this won't work because obviously A foo() is protected. But then why allow in the first place to have more accessible methods in the subclasses? Is there a case where this is helpful?
In general, subclasses can add methods to the interface they inherit from their parent class. Making a method more accessible is effectively adding to the interface.
But then why allow in the first place to have more accessible methods in the subclasses?
Because it can be useful for code that holds a subclass reference.
Is there a case where this is helpful?
One good example is Object.clone(), a protected method. All Java classes are subclasses, directly or indirectly, of Object. Subclasses that support cloning can choose to make this method public.
Foo foo1 = new Foo();
Foo foo2 = foo1.clone(); // Sometimes you're holding a subclass reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With