views:

375

answers:

9

I don't understand Access Modifiers in OOP. Why do we make for example in Java instance variables private and then use public getter and setter methods to access them? I mean what's the reasoning/logic behind this?

You still get to the instance variable but why use setter and getter methods when you can just make your variables public?

please excuse my ignorance as I am simply trying to understand why?

Thank you in advance. ;-)

A: 

You make class member variables private to control the way other code that you might not control can access and manipulate them.

If you're just writing toy code, it can be tricky to see the point, but when you write code that other people will use and depend on you will understand.

As a simple example say it's important that a class member variable is never set to null - say it will break your class. If you make the field public, any other code can set that variable to null, there's nothing you can do.

If you make it private and provide a setter method instead, you can protect the member from being set to null, can you can control whether you throw a checked/unchecked exception, or whether you just ignore the attempt.

Brabster
+9  A: 

This is called data or information hiding.

Basically, you don't want a user (read: other programmer, or yourself) poking in the internals of your class, because that makes it very hard to change things.

On the other hand, a clean separation between interface and implementation (theoretically) makes it easy to change something internally, without affecting any users of your class.

For example, suppose I have a Button control with a public String text field. Now everybody starts using my Button, but I realize that the button should actually be repainted on the screen whenever the text changes. I'm out of luck, because my object can't detect when text is assigned. Had I made it private and provided a setText() instead, I could just have added a repaint call to that setter method.

As another example, suppose I have some class that opens a file in its constructor and assigns it to a public FileStream file. The constructor throws an exception if the file could not be opened. The other methods in the class can therefore assume that this field is always valid. However, if somebody goes poking around in my class and sets file to null, all methods in my class will suddenly start crashing.

Thomas
+1  A: 

The difference is that with getters and setters you control how instance fields are accessed. You may provide defensive copies, immutable views, or even conversions of your instance fields. You have hidden your real implementation details from others. That's a good thing!

The more you hide while still making your interface friendly and useful, the better. Others don't need to know how things work (because they might be tempted to do things they aren't supposed to do); they just need to know that things work somehow.

polygenelubricants
+1  A: 

Another point is encapsulation - if you choose to change the way this variable is handled e.g. to always return/store a copy, you can do it in one place (the getter/setter) without breaking anything.

Tamar
+1  A: 

If your class is immutable, there is nothing wrong in exposing variables as public variables. (all will be public finals) and there is no rule that getter should always return the variable as it is.. or setter should set the variable as is.. You can wrap around ton of rules/modifiers etc around your private variable's access (data encapsulation)

ring bearer
+6  A: 

A very important point that is often overlooked: you don't have to provide a getter and a setter for every field! In fact, most fields should have neither, or only a getter (making them in effect read-only).

Having classes that consist of nothing but private properties and public getters and setters is just as bad a design as using public fields. It's an anti-pattern called anemic domain model. The point is that getters and setters allow you to add behaviour and logic to the model beyond the simple holding of data - and in many cases that means not having a getter or a setter (or both).

Michael Borgwardt
+1 you don't have to provide accessor, thats the key point
stacker
No, it's not just as bad as using public fields. I've worked with both, and found that having getters and setters to allow a lot more flexibility. It's still a really lousy way to design a class, but writing any real sort of class with public data members is much worse.
David Thornley
+1  A: 

In the first place, not all data members should have getters and setters, and I imagine you can see the virtue of keeping those variables private.

In the second place, most classes are more than random collections of data. They represent things that you should be able to reason independently about. Typically, this means that they have certain properties that a developer can depend on (frequently called "class invariants"). For example, a Rectangle class should have the property that drawing lines between the corner points yields lines at right angles to each other. If the points are public data members, it would be possible for any random application to change a point, and then you'd have a Rectangle that wasn't a rectangle. If you have a setter function, you can handle that properly.

In the third place, consider maintenance. At some point, you may want to modify a class implementation, and you may wonder how many things you'll have to change. If the data members are public, changing any detail of the implementation can break any of the programs that use that class. You're stuck. If there's getters and setters, you may be able to compensate for that, so that setting a value can do something more or less complicated in the internals to get the same effect as it previously had. If you have more abstract member functions, you'll have very little problem making changes.

David Thornley
+1: Good point about invariants. I suppose in a Rectangle class you shouldn't be able to set corners individually (rather you can move and stretch the rectangle).
UncleBens
A: 

These are the main advantage of using OOP, polymorphism, inheritance and encapsulation.

Encapsulation allow you to hide the implementation or data on your object by using private access modifier.

On the other hand you want to mutate the data thus creating setter method. Hope this helps.

Andre
A: 

You are talking about OOP basics. This theme worth of reading a nice book. Different blogs and forums (one of which is SO) are not the appropriate place for getting fundamental knowledge.

If you really want to get deep understanding of such basics which is vital for good developer then read related books. "Code Complete" or "Object Oriented Analysis" are worth to read them.

Roman