سؤال

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?

هل كانت مفيدة؟

المحلول

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.

نصائح أخرى

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.

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

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top