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
get and set
Started by farhanyun91, Aug 13 2010 07:46 PM
1 reply to this topic
#1
Posted 13 August 2010 - 07:46 PM
|
|
|
#2
Posted 13 August 2010 - 11:09 PM
They simply set and retrieve the values inside the object variables. For example if i have a class Car as below
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
I hope this gives you some idea,
Cheers!
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!


Sign In
Create Account


Back to top









