Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protected vs Public in terms of Inheritance in Java [duplicate]

Tags:

java

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?

like image 802
Lewis Briffa Avatar asked Mar 13 '15 21:03

Lewis Briffa


2 Answers

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.

like image 122
rgettman Avatar answered Sep 29 '22 23:09

rgettman


Use protected in a superclass only if you want your variable or method to be accessed or overridden by a subclass of that superclass but you do not want that variable or method to be accessed outside of the superclass or subclass (i.e. publicly).

Use public when you want your variable or method to be accessed by any class. Note that you should rarely have public non-final variables or public mutable variables.

if a program runs without any problems with a Protected access modifier set is there any need to change it to Public?

No, use the least accessible access modifiers for your variables and methods. Therefore if they are not required as public, do not make them public and only make them protected if they are required to be protected (i.e. required by subclasses). Otherwise make them private.

For the reasoning behind this, see the section "Item 13: Minimize the accessibility of classes and members" in Effective Java by Joshua Bloch: http://uet.vnu.edu.vn/~chauttm/e-books/java/Effective.Java.2nd.Edition.May.2008.3000th.Release.pdf

like image 25
Dermot Blair Avatar answered Sep 29 '22 22:09

Dermot Blair