“Setter” and “getter” methods.

Encapsulation: by not letting people access the field directly, and forcing to assign the model using a method, we can make sure that data within our objects have been validated and are correct.

In this lecture, I added to the main and car classes that I built in the previous lecture.

public class Main {

    public static void main(String[] args) {
	    Car porsche = new Car();
	    Car holden = new Car();
        porsche.setModel("911");
        System.out.println("Model is " + porsche.getModel());

    }
}
public class Car {

    private int doors;
    private int wheels;
    private String model;
    private String engine;
    private String colour;

    public void setModel(String model){
        String validModel = model.toLowerCase();
        if (validModel.equals("carrera") || validModel.equals("commodore")) {
            this.model = model;
        } else{
            this.model = ("unknown");
        }
    }

    public String getModel(){
        return this.model;
    }
}

Most of the work was done in the car class: by basically adding a setter method and a getter method. You can see that setModel and getModel are both used in the main class.

setModel accepts a string ‘model’. It converts it to lower case in order to performs validation. If  it is equal to either ‘carrera’ or ‘commodore’ then it sets this.model to the model name given. Else, it sets it to the string “unknown”.

One thing I’m not entirely sure about is the this.model part, is “this.” a syntactic thing?

getModel method basically returns this.model as defined in the previous method.

Thus in the main class where you try to declare a new car and set it as “911”, since that model is not known by the car class it prints out that it’s unknown.

So I guess if you have knowledge about the nature of cars you can work that into the car class itself and ensure that the work is done there to provide cleaner data or ease of use in the main class?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s