Thursday, July 26, 2018

Protected vs Public in terms of Inheritance in Java

Answer


Answer





When should one use Public over Protected in Java when creating Superclasses, if a program runs without any problems with a Protected access modifier set is there any need to change it to Public?


Answer



You should follow the Principle of Least Privilege.



This means that members should be assigned the minimum accessibility needed for the program to work.



If an unrelated class needs access, make it public. Typically this is done only for methods that provide managed access to data.




If the subclass is to be completely trusted in manipulating the data, and it needs it to work properly, you can make the member protected.



Else, make it private, so no other class can access it (without going through other more accessible methods that help encapsulate the data).



If your program works well when it's protected, then do not make it public. Consider making it private, with protected methods that access it, to encapsulate the data better.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...