Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

public variable..

 
Rajeev Ravindran
Ranch Hand
Posts: 455
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all,
can any1 tell me a situation where a variable should be declared as public...I mean, if I'm declaring a variable as private in a class and uses a public get method to access that variable i can access it right ???
thanx
raj.
 
Tim B.
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Raj,
In my humble opinion you make a good point, though I can think of two exceptions. Using getter and setter functions is in most cases a preferrable and more beautiful way to access variables of a class than declaring it public. Setting it to private instead of to protected is maybe a bit too much, but that of course depends on what you use your object for.
The first exception to your proposal is when you have an interface or class that is used to keep tracke of several constants which are used throughout your application. Then I suggest you use public (final) variables. The second reason I can think of to not use getter and setter methods is when performance and or size of the class file is a major issue. This second reason is more theoratical, but I guess you can say that accessing a variable through a method costs a (very little) bit more processing time than accessing it directly.
Just my two cents,
Tim
 
Ta Ri Ki Sun
Ranch Hand
Posts: 442
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by raj tvm:
hi all,
can any1 tell me a situation where a variable should be declared as public...I mean, if I'm declaring a variable as private in a class and uses a public get method to access that variable i can access it right ???
thanx
raj.


yep, the clean way is exactly what you said, private variables and public accessor methods where appropriate.
as for a situation where a variable might be declared public, well consider constants, they shouldn't be in danger of being modified, and all users of this constant will have the same value whenever they use it, hence the name constant, so it might be declared like this :

obviously you wont use this for the oil price or anything with even a remote possibility of changing
 
Rajeev Ravindran
Ranch Hand
Posts: 455
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thankQQQ tim and taariq for the instant responses .. it was a nice explanation.
raj
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic