Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Local Development Environments Advanced Tooling Code Generation

Mike B
Mike B
10,424 Points

Why do we need setters if the constructor already defines our private variables?

When we generated the getters and setters, I don't really understand the necessity for the setters. mSingerName and mSong are defined in the constructor...are the setters just so we can change the values for the private fields from outside the class?

3 Answers

Grigorij Schleifer
Grigorij Schleifer
10,365 Points

Hi Mike,

the principle behind getters and setters is called ENCAPSULATION. This is usefull to protect your data from beeing destroyed or incorrectly changed....

You use getters and setters to modificate private field variables of the class outside that class (you are totally right !).

Here is a little example:

public class MountainBike{
// public variable that can be changed from outside   
     public int numberOfWheels = 2;
}
::::::::::::::::::::::::::::::::::::
// a testclass that changes the number of wheels of the Mountainbike
public class Test {
    public static void main(String[]arg) {

        MountainBike mnt = new MountainBike();
        mnt.numberOfWheels = 0;
        System.out.println(mnt.numberOfWheels);
    }
}

The result is 0 !!! It makes no sence to ride a bike without wheels right !

If the variable numberOfWheels would be private, you could not change the value.

But you could use setters to set the number. And inside the setter method you can proof the number and throw an exception if the number is too small ...

Like this:

public class MountainBike{
    private int numberOfWheels = 2;

// getter
    public int getNumberOfWheels() {
    return numberOfWheels;
    }
// setter
    public int setNumberOfWheels(int newNumber) {
        if(newNumber < 2) {
            throw new IllegalArgumentException("There must be at least 2 wheels !");
        }
        return numberOfWheels;
    }
}
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
public class Test {
    public static void main(String[]arg) {

        MountainBike mnt = new MountainBike();
// setting the number of wheels to 1 throws an exception
        mnt.setNumberOfWheels(1);
        System.out.println(mnt.getNumberOfWheels());
    }
}

The result is

Exception in thread "main" java.lang.IllegalArgumentException: There must be at least 2 wheels !

Grigorij

Mike B
Mike B
10,424 Points

Thanks again, Grigorij!

I was going to reply to Preston asking "Then why make a variable private if we want to allow access outside the class but your example makes perfect sense! That example helped immensely!

"are the setters just so we can change the values for the private fields from outside the class?"

Yes, and the getters are so you can get the values outside the class.

Mike B
Mike B
10,424 Points

Thanks for the help...as I was typing the question, I figured that could be the only reason to add the setter

kabir k
PLUS
kabir k
Courses Plus Student 18,036 Points

The class constructor helps us to set the initial values of the information about our class (i.e. the private fields) so that they are required to be passed in upon the creation of an instance of the class.

The setters (or setter methods) help us to change or modify the values of the private fields from outside the class.