javagetter-setter

Java Public Var question


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?


Solution

  • 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;
        }
    }