Setter methods ◦ public methods that set the value of instance variables to a value specified by the call to the argument ◦ Setter methods do not violate the idea of private data you only change the variables you want ◦ Returns void (i.e. nothing) Getter methods ◦ public method that displays value of private variables ◦ Again, does not violate idea of private data You only display values you want to display ◦ Also called “accessor” or “query” methods Other objects can treat the object as a black box
class carSetter { private String licensePlate; private int speed; void setlicensePlate(String plate) //setter method { licensePlate = plate; } void setspeed(int ispeed) //setter method { speed=ispeed; } }//end class
class carSetter { private String licensePlate; private int speed; void setlicensePlate(String plate) //setter method { licensePlate = plate; } void setspeed(int ispeed) //setter method { speed=ispeed; } String getlicensePlate() //getter method { return licensePlate; } int getspeed() //getter method { return speed; } }//end class
class getter_Example { public static void main(String args[]) { carSetter a = new carSetter(); a.setlicensePlate("02 C 14"); a.setspeed(10); System.out.println(a.getlicensePlate() + " is moving at " + a.getspeed() + " mph."); }//main }//