I'm learning about overriding at the moment and I read that a private method cannot be overridden here
I also read that the access level cannot be more restrictive than the superclasses access level here
So what I'm wanting to know is, does this mean you can only override public methods? And you're new method must also be public?
Scenario
class A {
private void method1(){
....
}
}
class B extends A {
private void method1(){
....
}
}
Am I correct in saying this will be a compile time error because private methods cannot be overridden?
Scenario2
class A {
public void method1(){
....
}
}
class B extends A {
private void method1(){
....
}
}
Am I correct in saying this will also produce a compile time error because you the access level of method1() in B is more restrictive than method1() in A
Scenario3
class A {
public void method1(){
....
}
}
class B extends A {
public void method1(){
....
}
}
Final question, is this the only scenario methods can be overridden? (both access levels are public)
suppose the class:
class A {
public void method1() { }
protected void method2() { }
private void method3() { }
void method4() { }
}
then
class B extends A {
@Override
public void method1() {
// this method DOES override the Method1
}
@Override
protected void method2() {
// this method DOES override the Method2
super.method2();
}
private void method3() {
// this method DOES NOT override the Method3
}
@Override
void method4() {
// this method DOES override the Method4
super.method4();
}
}
and in all the cases your overridden method cannot be less visible than the method from the super class.
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