Java Reference
In-Depth Information
Unlike variables and methods, classes can only be given the public modifier or no modifier.
Encapsulation calls for the member variables (class or instance) to be given only private access, mean-
ing they are only directly accessible from within the same class. Then, the access modifiers of your
accessor methods can be set according to the demands of the program. For example, you might make
an employee's date of birth readable to everyone with a public accessor method, but restrict changes
to the Employee class with a private accessor method. The Product program might set price changes
to package protected, so subtypes of the Product and a Discounter class in the same package can
adjust the price.
By now you might be wondering what these accessor methods look like. They are commonly
referred to as “getter” and “setter” methods, because they are used to get and set variable values.
For this reason, they are given names like getName() or setPrice() . You'll look at getters and set-
ters in a bit more detail next.
getters
Getters are used to access variables' values for viewing only. You should create a getter method for
every private variable. Depending on the access level you want to give to the variable, you can set
the access modifier of its getter method. This is demonstrated with the Product class. The instance
variables are set to private, and public getter methods are added for each one.
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.productName = name;
this.productID = id;
this.productPrice = new BigDecimal(price);
}
 
public String getName(){
return this.productName;
}
 
public String getID(){
return this.productID;
}
 
public BigDecimal getPrice(){
return this.productPrice;
}
 
public String displayString() {
return "Product " + this.getID() + ": " + this.getName()
+ " costs " + this.getPrice();
}
}
 
Search WWH ::




Custom Search