Thursday 26 July 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

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...