By user759630


2011-07-10 03:20:10 8 Comments

How can I use the set and get methods, and why should I use them? Are they really helpful? And also can you give me examples of set and get methods?

15 comments

@Abimaran Kugathasan 2014-04-29 12:26:39

This answer is merged from another question.

Your getAge() method is called instance method in Java.

To invoke an instance method, you should have a object of the Class in which this method is defined.

For Example, If this method in a Class called Person, then

  1. Create a Person object using new operator

     Person p = new Person();
    
  2. To get the age of a Person object, use this method

    p.getAge()
    

@Abimaran Kugathasan 2014-04-29 12:32:59

Downvoted within a second. Not sure how they evaluate.

@displayname 2014-04-29 12:25:46

I think you want something like this:

public class Person {

  private int age;

  //public method to get the age variable
  public int getAge(){
       return this.age
  }

  //public method to set the age variable
  public void setAge(int age){
       this.age = age;
  }
}

You're simply calling such a method on an object instance. Such methods are useful especially if setting something is supposed to have side effects. E.g. if you want to react to certain events like:

  public void setAge(int age){

       this.age = age;

       double averageCigarettesPerYear = this.smokedCigarettes * 1.0 / age;

       if(averageCigarettesPerYear >= 7300.0) {
           this.eventBus.fire(new PersonSmokesTooMuchEvent(this));
       }
  }

Of course this can be dangerous if somebody forgets to call setAge(int) where he should and sets age directly using this.age.

@Chris Rae 2017-02-05 06:27:15

This is the nicest way of saying "no" I've ever seen.

@stivlo 2011-07-10 03:35:58

I want to add to other answers that setters can be used to prevent putting the object in an invalid state.

For instance let's suppose that I've to set a TaxId, modelled as a String. The first version of the setter can be as follows:

private String taxId;

public void setTaxId(String taxId) {
    this.taxId = taxId;
}

However we'd better prevent the use to set the object with an invalid taxId, so we can introduce a check:

private String taxId;

public void setTaxId(String taxId) throws IllegalArgumentException {
    if (isTaxIdValid(taxId)) {
        throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
    }
    this.taxId = taxId;
}

The next step, to improve the modularity of the program, is to make the TaxId itself as an Object, able to check itself.

private final TaxId taxId = new TaxId()

public void setTaxId(String taxIdString) throws IllegalArgumentException {
    taxId.set(taxIdString); //will throw exception if not valid
}

Similarly for the getter, what if we don't have a value yet? Maybe we want to have a different path, we could say:

public String getTaxId() throws IllegalStateException {
    return taxId.get(); //will throw exception if not set
}

@Erick Robertson 2011-07-10 04:05:35

-1 The first example is great. Remove the whole "improve the modularity of the program" part and I'll change to a +1.

@stivlo 2011-07-10 04:25:56

Actually I agree with Kent Pugh, as in the book Prefactoring: "Treat String as a primitive data type. Describe attributes with abstract data types, instead of as Strings." -- For example in a typical Customer class there might be several of these abstract types and some may have complex validation rules, that span several lines of code (sometimes hundreds). It's exactly what I did, I create several of these datatypes and they are general enough that I can re-use them through projects.

@stivlo 2011-07-10 04:53:58

I will try to explain this better. In an object oriented program a good way to think at a class could be in an anthropomorphized way. A domain expert in a domain, it must do something very well and only one thing. So a Customer class should be expert in Customers, not in postcodes, Vat Ids, Tax Ids, Municipalities, and shouldn't know how a phone number has to be formatted. All these concerns are separate small domains and should have a domain expert for each one of those. We don't want this code to pollute our main class.

@nem035 2014-10-16 14:55:03

Some benefits of using getters and setters (known as encapsulation or data-hiding):

(originally answered here)

1. The fields of a class can be made read-only (by only providing the getter) or write-only (by only providing the setter). This gives the class a total control of who gets to access/modify its fields.

Example:

class EncapsulationExample {
    private int readOnly = -1;  // this value can only be read, not altered
    private int writeOnly = 0;    // this value can only be changed, not viewed
    public int getReadOnly() {
        return readOnly;
    }
    public int setWriteOnly(int w) {
        writeOnly = w;
    }
}

2. The users of a class do not need to know how the class actually stores the data. This means data is separated and exists independently from the users thus allowing the code to be more easily modified and maintained. This allows the maintainers to make frequent changes like bug fixes, design and performance enhancements, all while not impacting users.

Furthermore, encapsulated resources are uniformly accessible to each user and have identical behavior independent of the user since this behavior is internally defined in the class.

Example (getting a value):

class EncapsulationExample {
    private int value;
    public int getValue() {     
        return value; // return the value
    }
}

Now what if I wanted to return twice the value instead? I can just alter my getter and all the code that is using my example doesn't need to change and will get twice the value:

class EncapsulationExample {
    private int value;
    public int getValue() {
        return value*2; // return twice the value
    }
}

3. Makes the code cleaner, more readable and easier to comprehend.

Here is an example:

No encapsulation:

class Box {
    int widthS; // width of the side
    int widthT; // width of the top
    // other stuff
}

// ...
Box b = new Box();
int w1 = b.widthS;  // Hm... what is widthS again? 
int w2 = b.widthT;  // Don't mistake the names. I should make sure I use the proper variable here!

With encapsulation:

class Box {
    private int widthS; // width of the side
    private int widthT; // width of the top
    public int getSideWidth() {
        return widthS;
    }
    public int getTopWIdth() {
        return widthT;
    }
    // other stuff
}

// ...
Box b = new Box();
int w1 = b.getSideWidth(); // Ok, this one gives me the width of the side
int w2 = b.getTopWidth(); // and this one gives me the width of the top. No confusion, whew!

Look how much more control you have on which information you are getting and how much clearer this is in the second example. Mind you, this example is trivial and in real-life the classes you would be dealing with a lot of resources being accessed by many different components. Thus, encapsulating the resources makes it clearer which ones we are accessing and in what way (getting or setting).

Here is good SO thread on this topic.

Here is good read on data encapsulation.

@SoyDuck 2018-03-30 19:05:39

why not make use a better variable name "sideWidth", you have to be retarded to not understand what "w1 = sideWidth;" mean.

@nem035 2018-03-30 19:20:45

@DuckSoy this example is trivial and shouldn't be taken at face value. The point is the general idea of separating your own naming convention and rules from the users of your API

@Madmenyo 2014-08-26 10:58:42

I don't see a simple answer to the second question (why) here. So here goes.

Let's say you have a public field that gets used very often in your code. Whenever you decide you need to do something extra before you give or set this field you have a problem. You have to create a special getter and setter for this field and change your complete code from using the field directly to using the getter and setters.

Now imagine you are developing a library widely used by many people. When you need to make a change like the above and set direct access of the field to private the code of all the people using this field will break.

Using getters and setters is about future planning of the code, it makes it more flexible. Of course you can use public fields, especially for simple classes that just hold some data. But it's always a good idea to just make the field privately and code a get and set method for it.

@Justin Ethier 2011-07-10 03:24:29

Set and Get methods are a pattern of data encapsulation. Instead of accessing class member variables directly, you define get methods to access these variables, and set methods to modify them. By encapsulating them in this manner, you have control over the public interface, should you need to change the inner workings of the class in the future.

For example, for a member variable:

Integer x;

You might have methods:

Integer getX(){ return x; }
void setX(Integer x){ this.x = x; }

chiccodoro also mentioned an important point. If you only want to allow read access to the field for any foreign classes, you can do that by only providing a public get method and keeping the set private or not providing a set at all.

@user759630 2011-07-09 22:47:37

from the looks of it, if I use set and get methods it would be easier to troubleshoot errors? am I right?

@Erick Robertson 2011-07-10 04:33:14

yes, and to avoid them in the first place.

@Justin Ethier 2011-07-10 13:31:50

Yes, for example, you can set breakpoints in these methods to see when the rest of your code attempts to access the underlying member variable

@chiccodoro 2014-04-29 12:46:05

what is not mentioned in this answer yet a very common case: If you only want to allow read access to the field for any foreign classes - you can do that by only providing a public getter method and keeping the setter private or not providing a setter at all.

@chiccodoro 2014-04-29 12:47:35

your example also does not show how the setter and getter could evolve over time (as you state in the text).

@mpop 2014-08-19 12:29:28

Also note that you can do error checking, along with bound checking.

@user3455363 2014-04-29 12:28:39

It looks like you trying to do something similar to C# if you want setAge create method
setAge(int age){ this.age = age;}

@subash 2014-04-29 12:28:12

public class Person{

private int age;

public int getAge(){
     return age;
}

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

i think this is you want.. and this also called pojo

@amit bhardwaj 2014-04-29 12:27:46

this is the code for set method

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

@Urs Reupke 2011-07-10 07:27:58

Above answers all assume that the object in question is an object with behaviour. An advanced strategy in OOP is to separate data objects (that do zip, only have fields) and behaviour objects.

With data objects, it is perfectly fine to omit getters and instead have public fields. They usually don't have setters, since they most commonly are immutable - their fields are set via the constructors, and never again. Have a look at Bob Martin's Clean Code or Pryce and Freeman's Growing OO Software... for details.

@Kaisar 2011-07-10 06:20:02

The benefits of get() set() methods are as follows ..

  1. You can serialize you object easily.
  2. You can create a persistent object from the containing class.
  3. You can convert the properties to JSON easily.
  4. In the DAO layer (Frameworks like Hibernate) you can directly save the object to DB.
  5. Easy understanding of object oriented concept.
  6. Needs in all design pattern except possibly in single tone pattern.
  7. Security for properties protecting direct access.
  8. Polymorphism, Encapsulation can be easily understood and implemented by this type of class.

Example:

private String personName;
private int personId;

    public void setPersonName(String name) throws Exception{
    if(!(name.equals("")||name=="")){
      this.personName = name;
    }
  }
  public String getPersonName(){
    return this.personName;
  }
  public void setPersonId(int id) throws Exception{
    this.personId = id;
  }
  public int getPersonId(){
    return this.personId;
  }

@user759630 2011-07-11 05:06:58

what does this operation do? it's my 1st time to encounter such a statement name.equals("")"

@Ben Xu 2011-07-10 03:41:16

just because the OOP rule: Data Hiding and Encapsulation. It is a very bad practice to declare a object's as public and change it on the fly in most situations. Also there are many other reasons , but the root is Encapsulation in OOP. and "buy a book or go read on Object Oriented Programming ", you will understand everything on this after you read any book on OOP.

@Erick Robertson 2011-07-10 04:07:45

-1 OP explicitly asked for examples.

@g051051 2011-07-10 03:25:42

Setters and getters are used to replace directly accessing member variables from external classes. if you use a setter and getter in accessing a property, you can include initialization, error checking, complex transformations, etc. Some examples:

private String x;

public void setX(String newX) {
    if (newX == null) {
        x = "";
    } else {
        x = newX;
    }
}

public String getX() {
    if (x == null) {
        return "";
    } else {
       return x;
    }
}

@Erick Robertson 2011-07-10 04:06:54

Interesting, since x cannot be null because of setX, so getX doesn't need to check for it. But point made, and anyone who understands this comment gets the whole point about getters and setters. +1

@g051051 2011-07-10 04:19:22

X would be null if getX is called before a call to setX.

@Erick Robertson 2011-07-10 04:24:35

Why isn't x just initialized to ""? Then you save the check in getX.

@g051051 2011-07-10 04:30:05

It certainly could be, and almost certainly should be, but doesn't have to be.

@Bohemian 2011-07-10 03:24:53

Having accessor methods is preferred to accessing fields directly, because it controls how fields are accessed (may impose data checking etc) and fits with interfaces (interfaces can not requires fields to be present, only methods).

@Bohemian 2011-07-10 05:18:19

gee... an example of a getter and setter. i don't know that would add much value since other posts had already done that

@xobicvap 2011-07-09 22:47:52

The above answers summarize the role of getters and setters better than I could, however I did want to add that your code should ideally be structured to reduce the use of pure getters and setters, i.e. those without complex constructions, validation, and so forth, as they break encapsulation. This doesn't mean you can't ever use them (stivlo's answer shows an example of a good use of getters and setters), just try to minimize how often you use them.

The problem is that getters and setters can act as a workaround for direct access of private data. Private data is called private because it's not meant to be shared with other objects; it's meant as a representation of the object's state. Allowing other objects to access an object's private fields defeats the entire purpose of setting it private in the first place. Moreover, you introduce coupling for every getter or setter you write. Consider this, for example:

private String foo;

public void setFoo(String bar) {
    this.foo = bar;
}

What happens if, somewhere down the road, you decide you don't need foo anymore, or you want to make it an integer? Every object that uses the setFoo method now needs to be changed along with foo.

Related Questions

Sponsored Content

85 Answered Questions

[SOLVED] Is Java "pass-by-reference" or "pass-by-value"?

47 Answered Questions

[SOLVED] Does a finally block always get executed in Java?

43 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

65 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3903354 View
  • 3361 Score
  • 65 Answer
  • Tags:   java random integer

38 Answered Questions

[SOLVED] Why use getters and setters/accessors?

55 Answered Questions

[SOLVED] Creating a memory leak with Java

57 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

22 Answered Questions

[SOLVED] Get current stack trace in Java

  • 2009-07-01 13:13:01
  • ripper234
  • 497894 View
  • 962 Score
  • 22 Answer
  • Tags:   stack-trace java

12 Answered Questions

8 Answered Questions

Sponsored Content