While inheriting, all instances of super class are of subclass.
Even after then we are unable to access private methods! Though, the instance is there.
Why is it so?
While inheriting, all instances of super class are of subclass.
Even after then we are unable to access private methods! Though, the instance is there.
Why is it so?
I'm not exactly sure what you are asking, but private methods are only accessible to the class itself, not to any classes that inherit from it. If you want the methods to be used by subclasses, you are looking for the protected
access keyword.
If you want to access superclass methods in a subclass, declare them protected
in the superclass.
private
methods (and fields) are only visible to the declaring class.
It's actually useful. If for no other reason, this way subclasses have a smaller set of callable functions (so they're easier to navigate). Moreover, the functions we make private, we do because they have no utility outside the original class. In this way, the superclass' creator can be sure that the functions aren't misused.
Sometimes, when you're creating a class, you want methods that encapsulate implementation details -- this is the point of private
methods. Because no-one else can use them, the original implementation is entirely free to change. (Which might include changing the signature of the private
method, or even removing it completely.