Jump to content

get and set

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
1 reply to this topic

#1
farhanyun91

farhanyun91

    Learning Programmer

  • Members
  • PipPipPip
  • 53 posts
please can anyone explain to me briefly about get and set.they are known as mutator(set) and get(accessor), am i right??i don't really understand the function of set and get.when to use get and when to use set.please someone help me out

#2
josep

josep

    Learning Programmer

  • Members
  • PipPipPip
  • 56 posts
They simply set and retrieve the values inside the object variables. For example if i have a class Car as below

public Class Car  {
private String color;
private String model;
private double mileage;

public void setColor(String color) {

this.color = color;
}

public String getColor() {
return color;
}

public void setModel(String model) {
this.model = model;
}

public String getModel() {
return model;
}

public void setMileage(double mileage) {
this.mileage = mileage;
}

public double getMileage() {
return mileage;
}

}

What happens here is that these set and get methods both set and retrieve the values inside the three variables of the car object.They also help in controlling how the state of the object is changed.Since the fields are private, the client of the Car class can only access the values through the set and get methods.

if you can make a small test class

public class CarTest {

public static void main(String []args) {
Car car = new Car();
car.setModel("BMW");
car.setColor("Red");
car.set(4000.78);

System.out.println("The car color is " + car.getColor());
System.out.printl("The car model is " + car.getModel());
System.out.println("The car mileage is " + car.getMileage());

}
}

I hope this gives you some idea,
Cheers!