Java Reference
In-Depth Information
If you tried this on your own, you might notice that this causes errors in the ProductProgram class.
This is because once the variables are assigned private access modifiers, the ProductProgram class
can no longer access the variable productPrice directly.
setters
Setters are the methods you use to modify the values of variables. Just like with getters, you
should create setters for every variable. Setters can replace the statements you used to use in
the constructor method. The Product class with the setter methods added is shown in the next
example.
import java.math.BigDecimal;
 
public class Product {
private String productName;
private String productID;
private BigDecimal productPrice;
 
public Product(String name, String id, String price) {
this.setName(name);
this.setID(id);
this.setPrice(price);
}
 
public String getName(){
return this.productName;
}
 
public void setName(String name){
this.productName = name;
}
 
public String getID(){
return this.productID;
}
 
public void setID(String id){
this.productID = id;
}
 
public BigDecimal getPrice(){
return this.productPrice;
}
 
public void setPrice(String price){
this.productPrice = new BigDecimal(price);
}
 
public String displayString() {
return "Product " + this.getID() + ": " + this.getName()
+ " costs " + this.getPrice();
}
}
 
Search WWH ::




Custom Search