Junior — Middle
Is it permissible to declare class fields with public visibility without restrictions?
sobes.tech AI
Answer from AI
Declaring class fields with public visibility without restrictions in Java is not recommended. This violates the principle of encapsulation — one of the key principles of object-oriented programming.
A best practice is to declare fields as private and provide access to them through getter and setter methods. This allows controlling access and modification of data, as well as facilitating maintenance and changes to the internal implementation of the class without affecting external code.
Example:
public class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Exceptions can be made for constants (static final), which are usually declared as public.