-3

I have this in one class:

if (people.count < 10)
    return false;

But count is undermarked with red saying Change the visibility of count to default

count is in another class as private. But I don't want to change it to default. I know it is a bad practice. How can I make it work without setter and getters?

Ankit
  • 6,554
  • 6
  • 49
  • 71
Sam
  • 900
  • 10
  • 18
  • 2
    why don't you want to use getters and setters? – Franklin Apr 11 '13 at 17:44
  • Besides getters and setters and public fields your only other (and really bad in this case) option is reflection – Jason Sperske Apr 11 '13 at 17:45
  • 1
    *How can I make it work without setter and getters?* Simple answer: **you can't**. This looks more like a whimsey than a design issue (that's why I downvote it). You could use reflection to handle the job but is a hack alternative instead of good design and practices (maybe that's up to you) – Luiggi Mendoza Apr 11 '13 at 17:46
  • Please post the class of the instance `people`. – Aubin Apr 11 '13 at 17:46
  • Thank you very much everyone! I will use getter: people.getCount() – Sam Apr 11 '13 at 17:55
  • You could have [Lombok](http://projectlombok.org/) set the getters and setters for you (just add a simple @Data annotation to your class and you get them automatically for all private fields) – Jason Sperske Apr 11 '13 at 17:56

4 Answers4

3

You can either change the visibility or expose a getter. Asking for another way to do this is literally asking, "how can I expose a variable without exposing it?" So, your call.

djechlin
  • 59,258
  • 35
  • 162
  • 290
1

The field count is private because it's encapsulated in the class. You're not intended to access it other than through a non-private member of the class.

Changing its access to 'default' would be easy but harmful.

Accessing it through a number of hacks (reflection, native methods, ...) would be more complex and still harmful.

Exposing a getter is easy and appropriate.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
0
if (people.getCount() < 10)
    return false;
Aubin
  • 14,617
  • 9
  • 61
  • 84
0

You only have the two choices; change the visibility or use getters and setters. The advantage of using getters and setters is that it adheres to the principle of encapsulation which in Java is important.

blackpanther
  • 10,998
  • 11
  • 48
  • 78