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?
You should
follow the rel="noreferrer">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