Java Reference
In-Depth Information
6.
Offering these three calculateAge() methods means that other classes using the Person class
can calculate a person's age based on the date the calculation occurs (how old is the person now?),
based on a given LocalDate (how old was the person when they graduated high school?), and
based on a given date, when the LocalDate class is not available to the other class or program
(how old was the person on a certain year, month, and day?). This functionality may make it more
reusable. By reusing one of the methods inside the others, you help improve maintainability.
information hiding
Information hiding, also referred to as encapsulation, is an object‐oriented practice that hides the
internal representation of objects. The main idea is to make member variables private, so they are
not directly accessible from outside of the class. Accessor methods are created to grant access to
view or modify the values of the variables. This gives the programmer control over how and when
variables can be accessed.
Encapsulation offers several advantages that make it standard recommended practice for all your
classes. First, as already mentioned, you can control the access to variables. For example, consider
the following small program:
import java.math.BigDecimal;
 
public class Product {
String productName;
String productID;
BigDecimal productPrice;
 
public Product(String name, String id, String price) {
this.productName = name;
this.productID = id;
this.productPrice = new BigDecimal(price);
}
 
public String displayString() {
return "Product " + this.productID + ": " + this.productName
+ " costs " + this.productPrice;
}
}
 
public class ProductProgram {
public static void main(String[] args) {
Product myWidget = new Product("Widget","WID0001","11.50");
myWidget.productPrice = new BigDecimal("-5.00");
System.out.println(myWidget.displayString());
}
}
In this example, you can create a product with a certain name, ID, and price as expected. However,
after the product is created, anyone can change the price, even to a price that doesn't make any
sense. It's best to restrict these changes in some way to avoid these problems, such as negative prices.
 
Search WWH ::




Custom Search