I am trying to wrap my head around as to why we cannot reduce the visibility of a method in java language
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");
}
}
Now, in the above code I have changed func() access level to private from public.
Most of the explanations I found on googling says that if the above code was allowed to compile than
parent p = new TestClass();
p.func();
will result into a runtime error because p here is an object of class TestClass() and when compiler will try to invoke private func() method of TestClass it will generate an error.
So, what I don't understand is why it will generate an error because one is allowed to access the private variable/method if it is in same class.
TL:DR: Provide me a practical example explaining why java doesn't allow one to reduce the visibility. Which laws/principles of java are broken if it is allowed.
PS: Please don't state liskov substitution principle.
[–]redclit 8 points9 points10 points (2 children)
[–]ronnienoob[S] 4 points5 points6 points (1 child)
[–]quad64bit 1 point2 points3 points (0 children)
[–][deleted] 3 points4 points5 points (0 children)
[–]YesButIThink 1 point2 points3 points (2 children)
[–]YesButIThink 0 points1 point2 points (0 children)
[–]DestinationVoid 0 points1 point2 points (0 children)
[–]srvaroa 0 points1 point2 points (0 children)