3
  • Why do we exactly need to use the set and get methods in our class that use private attributes?
  • When it is really used during our program process?
  • Can we still make it work without it (without changing the private attributes to public)?

This is an example of a source code when we are using the set and get methods:

public class Dog {

    private String dogName;
    private int dogAge;

    public Dog(String dogName, int dogAge) {
        this.dogName = dogName;
        this.dogAge = dogAge;
    }

    public String getDogName() {
        return dogName;
    }

    public void setDogName(String dogName) {
        this.dogName = dogName;
    }

    public int getDogAge() {
        return dogAge;
    }

    public void setDogAge(int dogAge) {
        this.dogAge = dogAge;
    }

    @Override
    public String toString() {
        return "Dog{" + "dogName=" + dogName + ", dogAge=" + dogAge + '}';
    }

}
3
  • 1
    It is a good way to design. Read about encapsulation Feb 5, 2015 at 11:15
  • 1
    You can have a look at Lombok if you don't want to write all your getters/setters by hand. Feb 5, 2015 at 11:20
  • 1
    Or just switch over to C# and write your getters/setters as automatic properties public string DogName { get; set; } ;) Feb 5, 2015 at 11:22

9 Answers 9

7

Why do we exactly need to use the set and get methods in our class that use private attributes?

If you want to hide details of implementation (encapsulation - a fundamental principle of object-oriented programming), you don't want someone from outside to access them, you only supply a method that returns some value, but you don't want to reveal implementation.

Also sometimes when you set a value, you need to change other variables that might be related, or changing some logic, it's not always a simple assignment statement.

When it is really used during our program process?

It's very hard to answer this question, it really depends on the program. You use setters and getters when you want to.. get, or set a value.

Can we still make it work without it?

Sure, it works when you have public fields instead of privates, in sense of design, it's recommended to start with private variables always, and change them only when you must.

7
  • could you modify your answer to clarify it more. Modify it by giving an example of each statement(answer) you made from my source code. For example, what do you mean by "implementation"? is it the private attributes (dogName, dogAge) or what exactly? in other words, use my source code to simplify what you just said. Thanks
    – askd
    Feb 5, 2015 at 11:27
  • @askd In your example, programmers can never know (if they know nothing about reflection) that you're using two class members (dogAge and dogName), it's not critical in your example, but think about sensitive objects, such as a BankAccount.. you don't want anyone to know how you store variables, how you modify them, you just want to give them a black box, you control the logic.
    – Maroun
    Feb 5, 2015 at 11:33
  • I have one more question, if you may. Can we access private variables directly from the same class. I mean without using methods to do that. If yes, how? I hope you can provide examples with it.
    – askd
    Feb 5, 2015 at 13:28
  • @askd Sure, just write this.dogAge... like in your setters and getters, return dogName; is the same as return this.dogName; - both are referring to the class member (the private member you have).
    – Maroun
    Feb 5, 2015 at 13:58
  • public class Dog { private String dogName; private int dogAge; this.dogName = "abc"; this.dogAge = 12; I tried this, but it gives me an error! illegal start of type. ; expected. cannot find symbol.
    – askd
    Feb 5, 2015 at 14:05
2

If you don't see the point of encapsulation, allow me to demonstrate with a "real life" example (which .

private boolean amIDrunk = true;

public boolean getAmIDrunk(Object asker){
    if (asker instanceof PoliceOfficer){
        return false;
    } else if (asker instanceof DrinkingBuddy ){
        return true;
    }
    return amIDrunk;
}

public void setAmIDrunk(boolean setter){
    if (hadLessThen10Beers()) {
        this.amIDrunk = false;
        return;
    }
    this.amIDrunk = setter;
}

Sure, this is a 'nitwit' example, but it's just to show that sometimes, just because you call a setter, there might be a reason not to set that value, and sometimes, when a getter is called, there might be a reason, you don't want to return the actual value.

Anyway, to continue in this example: having amIDrunk as a private variable, makes sure someone else doesn't declare you as 'drunk' by setting amIDrunk to true, without the implementation of your own set method to agree with it.

5
  • I like that. Simple and reasonable. This is exactly what I was looking for. Because I already knew about all the fancy words such as (encapsulation, implementation, Accessors and Mutators ...etc), but I didn't get the real concept behind using the set and get methods. All what I really wanted is to know when does it comes in handy regardless their definition. Thank you
    – askd
    Feb 5, 2015 at 11:43
  • @askd it's good to know definitions as well, it worth knowing these "fancy" words.
    – Maroun
    Feb 5, 2015 at 11:50
  • @askd this really is the answer to that question. In OOP, encapsulating an object's fields with getter and setter methods should be your default choice. Even if you do not see the need to do anything but this.field = value in a setter when you first implement an object, you may need to change that behavior in the future. Additionally, it makes it essentially impossible to mock the object in question for unit testing.
    – Chris Bode
    Feb 5, 2015 at 11:54
  • @MarounMaroun with all due respect, I have learned these "fancy" words multiple times and I know how to define it. But it didn't really help me much to find an answer for the questions that is going on in my mind. It is always good to give simple examples in order to comprehend a simple concept. Sometimes, using "fancy" words or general definitions can make simple things looks complicated.
    – askd
    Feb 5, 2015 at 12:04
  • @askd sure, it's very useful to see examples, but I wanted to say that don't be afraid of these words, use them to get used for them.. I hope answers here made it clear for you, best of luck.
    – Maroun
    Feb 5, 2015 at 12:06
2

I personally don't like the setters and getters and replace them with public fields if I can. However, there are techical reasons to keep them:

  • Mocking: Mocking frameworks such as Mockito or Easymock cannot mock or override direct field accesses
  • Proxies: For various reasons, proxies are used (Scopin in DI frameworks, logging, etc). Again, does not work with fields
  • JavaBeans based frameworks: Some frameworks for XML serialization don't support field access.

So, in many cases using the getters/setters just makes your life easier. However, if you are in charge of all code depending on your classes, just use Refactor->Encapsulate Field in eclipse (quite sure similar functionality exists in all major IDEs) as soon as you run into problems.

1

I recommend to read about Kotlin kotlinlang.org

You can write getters/setters for POJO in 1 line: e.g.

data class Customer(val name: String, val email: String, val company: String)
1
  • Kotlin is fixing tons of Java problems Apr 18, 2021 at 23:21
1

Another reason for using 'access methods' (setters and getters) is that it is a convention used in IoC (inversion of control). So frameworks like Spring etc. It may seem tedious to create them, but if you're using eclipse as an IDE for example you can generate setters and getters automatically (source|generate getters and setters).

Further your private member variables are important. Let's say you have :

public String telephoneNumber;

What is to stop someone doing this :

object.telephoneNumber = "not a telephone number".

If you used a setter you could do this :

public void setTelephoneNumber(final String telephoneNumber) {
   if (telephoneNumber==null||telephoneNumber.length()==0) {
      throw new IllegalArgumentException("you cannot supply null telephone numbers");
   }
   ... etc.
   this.telephoneNumber = telephoneNumber;
}

In this manner your telephoneNumber member variable will only ever hold a valid telephoneNumber. Your class is now totally self contained (encapsulated) because you are not relying on external classes to treat your member variables with respect.

3
  • This is also a good example. It answers my question. Thank you
    – askd
    Feb 5, 2015 at 12:17
  • After C# absence of Strring.isNullOrEmpty() in Java makes me cry sometimes Apr 18, 2021 at 23:22
  • @NikolayKlimchuk After spending a year on Python I can tell you that at least Java nulls are predictable. Try null checking a python boolean which is set to false, with the same code you'd check an object reference with :) I love python, but it's no Java.
    – Richard
    Apr 20, 2021 at 12:06
0

Setters and getters are used to achieve Encapsulation.

Yes, we can make it work without setters and getters.

0
  • Why do we exactly need to use the set and get methods in our class that use private attributes?

The Getters() and Setters() methods called also Accessors and Mutators are used so we can acces the private fields in a class from outside.

public class myClass(){
  public void newDog(){
    Dog d=new Dog("Foxy", 2);
    d.setDogAge(d.getDogAge()+1);//get the age of the dog and increment it
  }
}
  • When it is really used during our program process?

They are used when we need to achieve read(with getters)/write(with setters) operations with our private fields(like in the previous Example).

  • Can we still make it work without it?

Yes, of course we can if we declare those fields as public(default case):

String dogName;
int dogAge;

And the prvious example will be:

public class myClass(){
  public void newDog(){
    Dog d=new Dog("Foxy", 2);
    d.dogAge=d.dogAge+1;//get the age of the dog and increment it without getters and setters
  }
}

Take a look at TutorialsPoint's Encapsulation Tutorial for further information.

0

Getters and setters are indeed for the principle of encapsulation, there is a good explanation in the answer here. According to convention getter and setters cannot add any functionality besides storing and retrieving the property. Since this is the only thing these methods do, there is a growing support for setting these variables to public and access them directly, without these methods. Since these methods just expose them publicly, there is no functional difference. For convention, and some frameworks, getters and setters are expected.

You can always let your IDE (Eclipse, IntelliJ, Netbeans) write the getters and setters for you. But if you want your code to be DRY and easy to read you can also consider using Lombok, which makes the getters and setters for you automatically.

0

Why do we exactly need to use the set and get methods in our class that use private attributes?

This term "Encapsulation" comes under Object oriented programming. Encapsulation is you hide the implementation but giving access.

When it is really used during our program process?

Getters are there to get some value where setters are to set a value. In your code you set Dogs name as a String and age as an int. Finally you have getters to get the set value.

Can we still make it work without it?

Yes. You can make it work by changing the private declared variables to public. Actually private keyword will make that variable visible only to the class where it is declared.

This gives you an in detail explanation about Objects. http://docs.oracle.com/javase/tutorial/java/concepts/object.html

Not the answer you're looking for? Browse other questions tagged or ask your own question.