Why is it a good idea to have instance variables be private with public getter and setter methods?

Why is it a good idea to have instance variables be private with public getter and setter methods?

Instance variables are made private to force the users of those class to use methods to access them. In most cases there are plain getters and setters but other methods might be used as well.

Are public variables bad?

For smaller applications, global variables are not a problem. Sharing data inside the application using global variables will also help you minimize local variable creation and lesser memory usage. But for larger applications, using global variables are bad. It will make your application hard to maintain and read.

Why variables are declared private?

By making the variable a private data member, you can more easily ensure that the value is never negative. On the other hand, if the variable is public, another class could change it to a negative value which can cause other parts of the code to crash.

What’s the difference between a getter and a public variable?

As for getters–I still can’t come up with much of a difference between a getter and a public final variable. The problem here is that it’s bad OO in either case. You shouldn’t be asking for a value from an object and operating on it–you should be asking an object to do an operation for you.

Is it better to make a member variable public?

Are there any circumstances where it’s better to expose the inner workings of your class through making a member variable public, so any consumer of it can do things the designer never concieved of, leading to a feast of failure and a cornucopia of crashes? Sort of answers itself really that one does’t it?

Can a getter and setter be public in protected context?

In a protected context, its not terribly different to a public context. Foreign possibly rogue functions want access to the data-structure. So no, if they exist they operate like public getters/setters. if you have to perform sanity check before assigning value to the member like strings or array.

When to use Getter and setter in Java?

Using setter can be used to set the variable with checking the input. Keeping the instance varibale private, and getter and setter public is a form of Encapsulation getter and setter is also compatible with Java Beans standard,