Java accessor visibility

Java accessor visibility: When to make accessors public, and when to keep them private

“So how do you determine the proper visibility of an accessor method? My experience is that you should always strive to make accessors protected, so only subclasses can access the attributes. You should try to make accessors private if subclasses don’t need access to the attribute. Only when an external class or object needs to access an attribute should you make the appropriate getter or setter public. It is quite common for the visibility of corresponding getter and setter methods to be different: in the class Seminar, you see the getTitle() method has public visibility, yet setTitle() has private visibility.”

Leave a Reply

Your email address will not be published. Required fields are marked *