views:

115

answers:

5

Possible Duplicate:
Property and Encapsulation

NEWB Alert!!

I am starting with Android and Java and I am starting to understand it but I am wondering why I should use getters and setters and not just public variables?

I see many people make a private variable and create a get and set method.

What is the idea here?

A: 

I believe the idea is "information hiding" http://en.wikipedia.org/wiki/Information_hiding

It also serves to control the access to variables (provides an interface). For example, you can provide a getter but not a setter, so that they may be read but not written. Whereas if everything was public any thing could read and write to the variables.

Also important is any checking/validation need to set a variable. For example you have a String name that is not allowed to be empty but if it is public it could easily be forgotten and set as name = "". If you have a setter such as public boolean setName(String newName) you can check newNames length and return true or false if it passes and is set or not

Jacob
+1  A: 

The OOP concept involved is encapsulation (google it). Some of the advantages are: you can specify different access level for setters (mutators) and getters (accessors), for example public getter and private setter. Another advantage is that you can add another code other than changing or retrieving the value. For example, you may want to check the validity of the set value, or you want to throw exceptions or raise some events in response to changing the variable to certain value. If you implement these inside an accessor or mutators, you can also change their implementations without changing any code outside of the class.

Louis Rhys
A: 

The concept is called encapsulation.

What it attempts to do is to separate the inner structure of a class from its behaviour.

For example, suppose a class like this

public class Point{

  private   float x;
  private   float y;

  public float getX(){

     return x;
  }

  public float getY(){
    return y;
  }

  public float distanceToZero2(){

     return x*x + y*y
  }

  public float getAngle(){
    //havent considered the x = 0 case. 
    return atan(y/x);

   }

public boolean isInFirstQuad(){

   return x>0 && y>0;
}
}

In this case, encapsulation hides the inner structure of the class, and exposes only the operations available to a Point. If you dont like it, you can change its inner structure and mantain its behaviour (for example, changing carthesian coordinates to polar coordinates).

Anyoune who uses this class wont care about it, he /she will be happy that they have a Point class with this functionality.

Tom
+8  A: 

Its called encapsulation and the concept is central to object oriented programming. The idea is that you hide the implementation of your class and expose only the contract i.e. hide the how and only expose the what. You hide the variables by making them private and provide public setters-getters and other public methods which the clients invoke to communicate with your class. They are not tied to the actual implementation of the methods or how you store your variables.

For example, suppose you had this class where you stored a phone number as a Long object:

public class ContactInfo {
    private Long phoneNo;
    public Long getPhoneNo() {
        return phoneNo;
    }
    public void setPhoneNo(Long phoneNo) {
        this.phoneNo = phoneNo;
    }
}

Since the clients of the class only see the getter/setter, you can easily change the implementation of the class/methods by switching the phone number representation to a PhoneNumber object. Clients of ContactInfo wouldn't get affected at all:

public class ContactInfo {
    private PhoneNumber phoneNo;
    public Long getPhoneNo() {
        return phoneNo.getNumber();
    }
    public void setPhoneNo(Long phoneNo) {
        this.phoneNo = new PhoneNumber(phoneNo);
    }
}
public class PhoneNumber {
    private Long number;
    public PhoneNumber(Long number) {
        this.number = number;
    }
    public Long getNumber() {
        return number;
    }
}
Samit G.
+1. Note that this does _not_ mean you should always provide a getter and setter for every field; in some cases, your design may call for fields with no public access at all.
Feanor
@Feanor. Agreed! That's a case for private variables. The OP however wanted to know why to go for public getters/setters rather than public variables, so the answer assumes that public access is desired.
Samit G.
@SamG: Most definitely, I think your answer is clear. When I started learning Java I didn't understand that one might not want to expose every single field via get/set. I figured since the OP mentioned newbiness, it would be worthwhile to add that little piece.
Feanor
A: 

Asides the encapsulation, you can also control the value get or set to your variable in some cases. For example, you want to validate the value of an age variable which should be >=1

class Person {
   private int age = Integer.MIN_VALUE;

public void setAge(int age){
   if(age>=1)
      this.age = age;
}


public int getAge(){
   return age;
}
}
Truong Ha