I got this compiler error:
You cannot reduce the visibility of a inherited method.
I have the following code
class Parent {
public void func() {
System.out.println("in Parent");
}
}
public class TestClass extends Parent {
public static void main(String args[]) {
parent obj=new TestClass();
obj.addTest();
}
private void func() {
System.out.println("in child");
}
}
Here parent class has func() method which is public and overridden by the subclass TestClass which is private. Now the compiler throws the error that I cannot the reduce the visibility. To say technically, whenever I create a object of TestClass assigning to the type parent object, since the func() method is overridden, TestClass’s func() is going to get called always, then why we should take care of visibility? whats the reason behind this error ? Can someone explain me clearly ?
It’s because the subclass has visibility of
privatefor thevoid func()method, but the superclass has visibilitypublic.If your code was allowed to compile, it would explode at runtime if you did this:
To “fix” this, make the subclass’s
funcmethodpublic:And please use standard naming conventions; in this case “classes should start with a capital letter” – i.e
Parentnotparent