• Post Reply Bookmark Topic Watch Topic
  • New Topic

why while creating immutable class, fields are declared as private?  RSS feed

 
khwaish singh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
while creating immutable class all the fields are declared as final so that their value cant be modified.this is okay but why we also declared them as private
 
Junilu Lacar
Sheriff
Posts: 11494
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't have to declare them as private although that's the normal practice for instance members (fields). There are no hard and fast rules. You have to think about why you need to expose something as public and decide whether that's a good idea or not. A few things could factor into that decision: Java coding conventions (using getters instead of providing direct access to a field), encapsulation / information hiding, etc.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!