1
votes

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?

4
why don't you want to use getters and setters? - Franklin
Besides getters and setters and public fields your only other (and really bad in this case) option is reflection - Jason Sperske
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
Please post the class of the instance people. - Aubin
Thank you very much everyone! I will use getter: people.getCount() - Sam

4 Answers

3
votes

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.

1
votes

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.

0
votes
if (people.getCount() < 10)
    return false;
0
votes

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.