Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: When NOT to use `private`

Since it's regarded bad OO practice to have public variables in a class (instead, use getters and setters) then why not use private on all variables? Why does Java even permit using public if it's bad practice?

(This doesn't apply to functions, obviously)

like image 585
Name McChange Avatar asked Dec 09 '22 17:12

Name McChange


2 Answers

A public static final variable is a good reason for example. Like a constant.

like image 127
Petar Minchev Avatar answered Dec 11 '22 05:12

Petar Minchev


Having a public or private field is a design decision. The language itself is supposed to enable programmers to make their own design decisions, not enforce a design that the developer or team may not necessarily want to implement.

The more flexible the language, the more powerful it is. It's up to the project manager, the team, or the individual developer to determine the most appropriate way for a field to be accessed.

like image 25
asteri Avatar answered Dec 11 '22 07:12

asteri