Download 6. Design and test OOPs

Document related concepts
no text concepts found
Transcript
Chapter 6
How to define
and use classes
YG - CS170
1
Objectives
Skills
 Code the instance variables, constructors, and methods of a class that
defines an object.
 Code a class that creates objects from a user-defined class and then
uses the methods of the objects to accomplish the required tasks.
 Code a class that contains static fields and methods, and call these
fields and methods from other classes.
 Given the Java code for an application that uses any of the language
elements presented in this chapter, explain what each statement in the
application does.
YG - CS170
2
Objectives (continued)
Knowledge
 Describe the architecture commonly used for object-oriented
programs.
 Describe the concept of encapsulation and explain its importance to
object-oriented programming.
 Differentiate between an object’s identity and its state.
 Describe the basic components of a class.
 Explain what an instance variable is.
 Explain when a default constructor is used and what it does.
 Describe a signature of a constructor or method, and explain what
overloading means.
 List four ways you can use the this keyword within a class definition.
YG - CS170
3
Objectives (continued)
 Explain the difference between how primitive types an reference
types are passed to a method
 Explain how static fields and static methods differ from instance
variables and regular methods.
 Explain what a static initialization block is and when it’s executed.
YG - CS170
4
The architecture of a three-tiered application
Presentation
layer
Presentation
classes
Middle layer
Business
classes
Database layer
Database
classes
YG - CS170
Database
5
How classes can be used to structure an
application
 To simplify development and maintenance, many applications use
a three-tiered architecture to separate the application’s user
interface, business rules, and database processing.
 Classes are used to implement the functions performed at each
layer of the architecture.
 The classes in the presentation layer control the application’s user
interface.
 The classes in the database layer handle all of the application’s
data processing.
 The classes in the middle layer, which is sometimes called the
business rules layer, act as an interface between the classes in the
presentation and database layers. The objects created from these
business classes are called business objects.
YG - CS170
6
A class diagram for the Product class
Product
-code: String
-description: String
-price: double
Fields
+setCode(String)
+getCode(): String
+setDescription(String)
+getDescription(): String
+setPrice(double)
+getPrice(): double
+getFormattedPrice(): String
Methods
YG - CS170
7
Concept of Encapsulation
 What is encapsulation?
- data and functions/methods are packaged
together in the class normally with the same scope
of the accessibility in the memory
 Why encapsulation
- Objects no longer need to be dependent upon
any “outside” functions and data after the creation
- Provide ADT (Abstract Data Types)
- Easier in coding
- Promote standards in OOP
YG - CS170
8
How encapsulation works
 The fields of a class store the data of a class.
 The methods of a class define the tasks that a class can perform.
Often, these methods provide a way to work with the fields of a
class.
 Encapsulation is one of the fundamental concepts of objectoriented programming. This means that the class controls which
of its fields and methods can be accessed by other classes.
 With encapsulation, the fields in a class can be hidden from other
classes, and the methods in a class can be modified or improved
without changing the way that other classes use them.
YG - CS170
9
UML diagramming notes
 UML (Unified Modeling Language) is the industry standard used to
describe the classes and objects of an object-oriented application.
 The minus sign (-) in a UML class diagram marks the fields and
methods that can’t be accessed by other classes, while the plus sign
(+) signifies that access is allowed.
 For each field, the name is given, followed by a colon, followed by
the data type.
 For each method, the name is given, followed by a set of
parentheses, followed by a colon and the data type of the value
that’s going to be returned.
 If a method doesn’t require any parameters, the parentheses are left
empty. Otherwise, the data type of each parameter is listed in them.
YG - CS170
10
The relationship between a class and its objects
Product
-code: String
-description: String
-price: double
product1
-code = "java"
-description = "Murach's Beginning Java 2"
-price = 49.50
product2
-code = "mcb2"
-description = "Murach's Mainframe COBOL"
-price = 59.50
YG - CS170
11
The relationship between a class and its objects
(continued)
 A class can be thought of as a template from which objects are
made.
 An object diagram provides the name of the object and the values
of the fields.
 Once an instance of a class is created, it has an identity (a unique
address) and a state (the values that it holds).
 Although an object’s state may change throughout a program, its
identity never does.
YG - CS170
12
Classes vs. Objects
 Class is a data structure that encapsulates data and
functions.
 Data in a class are called member data, class
variables, instance variables, or fields.
 Functions in a class are called member functions or
methods. Constructors are special methods.
 Objects are the instance of a class. Creation of the
objects and instantiation of the objects are all referring
to memory allocation to hold the data and methods of
the objects. In Java, all objects are created
dynamically using new operator. For example:
ClassName ObjName = new ClassName();
YG - CS170
13
The Product class
import java.text.NumberFormat;
public class Product
{
// the instance variables
private String code;
private String description;
private double price;
// the constructor
public Product()
{
code = "";
description = "";
price = 0;
}
YG - CS170
14
The Product class (continued)
// the set and get accessors for the code variable
public void setCode(String code)
{
this.code = code;
}
public String getCode()
{
return code;
}
// the set and get accessors
// for the description variable
public void setDescription(String description)
{
this.description = description;
}
public String getDescription()
{
return description;
}
YG - CS170
15
The Product class (continued)
// the set and get accessors for the price variable
public void setPrice(double price)
{
this.price = price;
}
public double getPrice()
{
return price;
}
// a custom get accessor for the price variable
public String getFormattedPrice()
{
NumberFormat currency =
NumberFormat.getCurrencyInstance();
return currency.format(price);
}
}
YG - CS170
16
The syntax for declaring instance variables
public|private primitiveType|ClassName variableName;
Examples
private
private
private
private
double price;
int quantity;
String code;
Product product;
YG - CS170
17
Where you can declare instance variables
public class Product
{
//common to code instance variables here
private String code;
private String description;
private double price;
//the constructors and methods of the class
public Product(){}
public void setCode(String code){}
public String getCode(){ return code; }
public void setDescription(String description){}
public String getDescription(){ return description; }
public void setPrice(double price){}
public double getPrice(){ return price; }
public String getFormattedPrice()
{ return formattedPrice; }
//also possible to code instance variables here
private int test;
}
YG - CS170
18
How to code instance variables
 An instance variable may be a primitive data type, an object
created from a Java class such as the String class, or an object
created from a user-defined class such as the Product class.
 To prevent other classes from accessing instance variables, use the
private keyword to declare them as private.
YG - CS170
19
The syntax for coding constructors
public ClassName([parameterList])
{
// the statements of the constructor
}
A constructor that assigns default values
public Product()
{
code = "";
description = "";
price = 0.0;
}
YG - CS170
20
A custom constructor with three parameters
public Product(String code, String description,
double price)
{
this.code = code;
this.description = description;
this.price = price;
}
Another way to code the constructor shown
above
public Product(String c, String d, double p)
{
code = c;
description = d;
price = p;
}
YG - CS170
21
A constructor with one parameter
public Product(String code)
{
this.code = code;
Product p = ProductDB.getProduct(code);
description = p.getDescription();
price = p.getPrice();
}
YG - CS170
22
Characteristics of Constructors
 A special method that has the same name of the class
without return type, not even void.
 Constructor will be automatically called whenever an
object is created.
 Like a method, constructor can be overloaded for the
flexibility of the object creation.
 A super class constructor can be called by a sub class
object as:
super();
YG - CS170
23
How to code constructors
 The constructor must use the same name and capitalization as the
name of the class.
 If you don’t code a constructor, Java will create a default
constructor that initializes all numeric types to zero, all boolean
types to false, and all objects to null.
 To code a constructor that has parameters, code a data type and
name for each parameter within the parentheses that follow the
class name.
 The name of the class combined with the parameter list forms the
signature of the constructor.
 Although you can code more than one constructor per class, each
constructor must have a unique signature.
 The this keyword can be used to refer to an instance variable of
the current object.
YG - CS170
24
The syntax for coding a method
public|private returnType methodName([parameterList])
{
// the statements of the method
}
A method that doesn’t accept parameters or
return data
public void printToConsole()
{
System.out.println(code + "|" + description
+ "|" + price);
}
A get method that returns a string
public String getCode()
{
return code;
}
YG - CS170
25
get methods
• In OOP, particularly in Java, get() means to return one of object’s
member data
• get() usually has a return type and takes no argument
• Use meaningful name for a get() method
A get method that returns a double value
public double getPrice()
{
return price;
}
A custom get method
public String getFormattedPrice()
{
NumberFormat currency =
NumberFormat.getCurrencyInstance();
return currency.format(price);
}
YG - CS170
26
set methods
• In OOP, particularly in Java, set() means to set object’s member data
• set() usually has void return and takes argument(s) to set the member
data
• set() also checks the validity of the data before it sets
• Use meaningful name for a set() method
A set method
public void setCode(String code)
{
this.code = code;
}
Another way to code a set method
public void setCode(String productCode)
{
code = productCode;
YG - CS170
}
27
How to code methods
 To allow other classes to access a method, use the public
keyword. To prevent other classes from accessing a method, use
the private keyword.
 To code a method that doesn’t return data, use the void keyword
for the return type.
 To code a method that returns data, code a return type in the
method declaration and code a return statement in the body of the
method.
 When you name a method, you should start each name with a
verb.
 It’s a common coding practice to use the verb set for methods that
set the values of instance variables and to use the verb get for
methods that return the values of instance variables.
YG - CS170
28
How to overload methods
 When two or more methods have the same name but different
parameter lists, the methods are overloaded.
 It’s common to use overloaded methods to provide two or more
versions of a method that work with different data types or that
supply default values for omitted parameters.
Example 1: A method that accepts one argument
public void printToConsole(String sep)
{
System.out.println(code + sep + description
+ sep + price);
}
YG - CS170
29
Example 2: An overloaded method that provides
a default value
public void printToConsole()
{
printToConsole("|");
// this calls the method in example 1
}
Example 3: An overloaded method with two
arguments
public void printToConsole(String sep, boolean
printLineAfter)
{
printToConsole(sep);
// this calls the method in example 1
if (printLineAfter)
System.out.println();
}
YG - CS170
30
Code that calls the PrintToConsole methods
Product p = ProductDB.getProduct("java");
p.printToConsole();
p.printToConsole("
p.printToConsole("
", true);
");
The console
java|Murach's Beginning Java 2|49.5
java
Murach's Beginning Java 2
49.5
java
49.5
Murach's Beginning Java 2
YG - CS170
31
The syntax for using the this keyword
this.variableName
// refers to an instance variable of the current object
this(argumentList);
// calls another constructor of the same class
this.methodName(argumentList)
// calls a method of the current object
objectName.methodName(this)
// passes the current object to a method
ClassName.methodName(this)
// passes the current object to a static method
YG - CS170
32
How to refer to instance variables with the this
keyword
public Product(String code, String description,
double price)
{
this.code = code;
this.description = description;
this.price = price;
}
How to refer to methods
public String getFormattedPrice()
{
NumberFormat currency =
NumberFormat.getCurrencyInstance();
return currency.format(this.getPrice);
}
YG - CS170
33
How to call a constructor using the this keyword
public Product()
{
this("", "", 0.0);
}
How to send the current object to a method
public void print()
{
System.out.println(this);
}
How to send the current object to a static method
public void save()
{
ProductDB.saveProduct(this);
}
YG - CS170
34
How to use the this keyword
 Since Java implicitly uses the this keyword for instance variables
and methods, you don’t need to explicitly code it unless a
parameter has the same name as an instance variable.
 If you use the this keyword to call another constructor, the
statement must be the first statement in the constructor.
YG - CS170
35
How to create an object in two statements
ClassName variableName;
variableName = new ClassName(argumentList);
Example with no arguments
Product product;
product = new Product();
YG - CS170
36
How to create an object in one statement
ClassName variableName = new ClassName(argumentList);
Example 1: No arguments
Product product = new Product();
Example 2: One literal argument
Product product = new Product("java");
Example 3: One variable argument
Product product = new Product(productCode);
Example 4: Three arguments
Product product = new Product(code, description, price);
YG - CS170
37
How to create an object
 To create an object, you use the new keyword to create a new
instance of a class.
 Each time the new keyword creates an object, Java calls the
constructor for the object, which initializes the instance variables
for the object.
 After you create an object, you assign it to a variable. When you
do, a reference to the object is stored in the variable. Then, you
can use the variable to refer to the object.
 To send arguments to the constructor, code the arguments within
the parentheses that follow the class name, separated by commas.
 The arguments you send must be in the sequence and have the
data types called for by the constructor.
YG - CS170
38
How to call a method
objectName.methodName(argumentList)
Example 1: Sends and returns no arguments
product.printToConsole();
Example 2: Sends one argument and returns no
arguments
product.setCode(productCode);
Example 3: Sends no arguments and returns a
double value
double price = product.getPrice();
YG - CS170
39
Example 4: Sends an argument and returns a
String object
String formattedPrice =
product.getFormattedPrice(includeDollarSign);
Example 5: A method call within an expression
String message = "Code: " + product.getCode() + "\n\n"
+ "Press Enter to continue or enter 'x' to exit:";
YG - CS170
40
How to call the methods of an object
 To call a method that doesn’t accept arguments, type an empty set
of parentheses after the method name.
 To call a method that accepts arguments, enter the arguments
between the parentheses that follow the method name, separated
by commas.
 The data type of each argument must match the data type that’s
specified by the method’s parameters.
 If a method returns a value, you can code an assignment statement
to assign the return value to a variable. The data type of the
variable must match the data type of the return value.
YG - CS170
41
Primitive types are passed by value
A method that changes the value of a double type
static double increasePrice(double price)
// returns a double
{
return price *= 1.1;
}
Code that calls the method
double price = 49.5;
price = increasePrice(price);
// reassignment statement
System.out.println("price: " + price);
Result
price: 54.45
YG - CS170
42
Objects are passed by reference
A method that changes a value stored in a Product object
static void increasePrice(Product product)
// no return value
{
double price = product.getPrice();
product.setPrice(price *= 1.1);
}
Code that calls the method
Product product = ProductDB.getProduct("java");
System.out.println("product.getPrice(): " +
product.getPrice());
increasePrice(product);
// no reassignment necessary
System.out.println("product.getPrice(): " +
product.getPrice());
Result
product.getPrice(): 49.5
product.getPrice(): 54.45
YG - CS170
43
How primitive types and reference types are
passed to a method
 When a primitive type is passed to a method, it is passed by value.
That means the method can’t change the value of the variable
itself. Instead, the method must return a new value that gets stored
in the variable.
 When a reference type (an object) is passed to a method, it is
passed by reference. That means that the method can change the
data in the object itself, so a new value doesn’t need to be returned
by the method.
YG - CS170
44
The ProductDB class
public class ProductDB
{
public static Product getProduct(String productCode)
{
// create the Product object
Product p = new Product();
// fill the Product object with data
p.setCode(productCode);
if (productCode.equalsIgnoreCase("java"))
{
p.setDescription("Murach's Beginning Java 2");
p.setPrice(49.50);
}
else if (productCode.equalsIgnoreCase("jsps"))
{
p.setDescription(
"Murach's Java Servlets and JSP");
p.setPrice(49.50);
}
YG - CS170
45
The ProductDB class (continued)
else if (productCode.equalsIgnoreCase("mcb2"))
{
p.setDescription("Murach's Mainframe COBOL");
p.setPrice(59.50);
}
else
{
p.setDescription("Unknown");
}
return p;
}
}
YG - CS170
46
The console for the ProductApp class
Welcome to the Product Selector
Enter product code: java
SELECTED PRODUCT
Description: Murach's Beginning Java 2
Price:
$49.50
Continue? (y/n):
YG - CS170
47
The ProductApp class
import java.util.Scanner;
public class ProductApp
{
public static void main(String args[])
{
// display a welcome message
System.out.println(
"Welcome to the Product Selector");
System.out.println();
// display 1 or more products
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
YG - CS170
48
The ProductApp class (continued)
// get the input from the user
System.out.print("Enter product code: ");
String productCode = sc.next();
// read the product code
sc.nextLine();
// discard any other data entered on the line
// get the Product object
Product product =
ProductDB.getProduct(productCode);
// display the output
System.out.println();
System.out.println("SELECTED PRODUCT");
System.out.println("Description: " +
product.getDescription());
System.out.println("Price:
" +
product.getFormattedPrice());
System.out.println();
YG - CS170
49
The ProductApp class (continued)
// see if the user wants to continue
System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}
YG - CS170
50
Static Fields
 What is a static field?
a variable that is not associated with any instance of
the class, therefore it’s a class-wide field/variable/data
a variable that can be used without creation of the
object
a private static field can be only use within the current
class
can be constant (final), so it’s value cannot be
modified; must be initialized when declaring
 Why static fields?
keep tracking class-wide information
Convenient to use and save memory
Be careful data encapsulation in using static fields
YG - CS170
51
How to declare static fields
private static int numberOfObjects = 0;
private static double majorityPercent = .51;
public static final int DAYS_IN_JANUARY = 31;
public static final float EARTH_MASS_IN_KG = 5.972e24F;
YG - CS170
52
A class that contains a static constant and a static
method
public class FinancialCalculations
{
public static final int MONTHS_IN_YEAR = 12;
public static double calculateFutureValue(
double monthlyPayment, double yearlyInterestRate,
int years)
{
int months = years * MONTHS_IN_YEAR;
double monthlyInterestRate =
yearlyInterestRate/MONTHS_IN_YEAR/100;
double futureValue = 0;
for (int i = 1; i <= months; i++)
futureValue = (futureValue + monthlyPayment)
* (1 + monthlyInterestRate);
return futureValue;
}
}
YG - CS170
53
The Product class with a static variable and a
static method
public class Product
{
private String code;
private String description;
private double price;
private static int objectCount = 0; // declare a static variable
public Product()
{
code = "";
description = "";
price = 0;
objectCount++;
}
// update the static variable
public static int getObjectCount() // get the static variable
{
return objectCount;
}
...
YG - CS170
54
How to code static fields and methods
 You can use the static keyword to code static fields and static
methods.
 Since static fields and static methods belong to the class, not to an
object created from the class, they are sometimes called class
fields and class methods.
 When you code a static method, you can only use static fields and
fields that are defined in the method.
 You can’t use instance variables in a static method because they
belong to an instance of the class, not to the class as a whole.
YG - CS170
55
The syntax for calling a static field or method
className.FINAL_FIELD_NAME
className.fieldName
className.methodName(argumentList)
How to call static fields
From the Java API
Math.PI
From a user-defined class
FinancialCalculations.MONTHS_IN_YEAR
Product.objectCount
// if objectCount is declared as public
YG - CS170
56
How to call static methods
From the Java API
NumberFormat currency =
NumberFormat.getCurrencyInstance();
int quantity = Integer.parseInt(inputQuantity);
double rSquared = Math.pow(r, 2);
From user-defined classes
double futureValue =
FinancialCalculations.calculateFutureValue(
monthlyPayment, yearlyInterestRate, years);
int productCount = Product.getObjectCount();
A statement that calls a static field and a static
method
double area = Math.PI * Math.pow(r, 2);
// pi times r squared
YG - CS170
57
How to call static fields and methods
 To call a static field, type the name of the class, followed by the
dot operator, followed by the name of the static field.
 To call a static method, type the name of the class, followed by
the dot operator, followed by the name of the static method,
followed by a set of parentheses.
 If the method you’re calling requires arguments, code the
arguments within the parentheses, separating multiple arguments
with commas.
YG - CS170
58
The syntax for coding a static initialization block
public class className
{
// any field declarations
static
{
// any initialization statements for static fields
}
// the rest of the class
YG - CS170
59
A class that uses a static initialization block
public class ProductDB
{
private static Connection connection;
// static variable
// the static initialization block
static
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:MurachProducts";
String user = "Admin";
String password = "";
connection = DriverManager.getConnection(url,
user, password);
}
YG - CS170
60
A class that uses a static initialization block
(continued)
catch (Exception e)
{
System.out.println(
"Error connecting to database.");
}
}
// static methods that use the Connection object
public static Product get(String code){}
public static boolean add(Product product){}
public static boolean update(Product product){}
public static boolean delete(String code){}
}
YG - CS170
61
How to code a static initialization block
 To initialize the static variables of a class, you typically code the
values in the declarations. But if a variable can’t be initialized in a
single statement, you can code a static initialization block that’s
executed when another class first calls any method of the static
class.
 When a class is loaded, Java initializes all static variables and
constants of the class. Then, it executes all static initialization
blocks in the order in which they appear.
 A class is loaded when one of its constructors or static methods is
called.
YG - CS170
62
The console for the Line Item application
Welcome to the Line Item Calculator
Enter product code: java
Enter quantity:
2
LINE ITEM
Code:
Description:
Price:
Quantity:
Total:
java
Murach's Beginning Java 2
$49.50
2
$99.00
Continue? (y/n):
YG - CS170
63
The class diagrams
Product
LineItem
-code: String
-description: String
-price: double
-product: Product
-quantity: int
-total: double
+setCode(String)
+getCode(): String
+setDescription(String)
+getDescription(): String
+setPrice(double)
+getPrice(): double
+getFormattedPrice(): String
+setProduct(Product)
+getProduct(): Product
+setQuantity(int)
+getQuantity(): int
+getTotal(): double
-calculateTotal()
+getFormattedTotal(): String
Validator
+getString(Scanner,
String): String
+getint(Scanner, String): int
+getint(Scanner, String,
int, int): int
+getDouble(Scanner,
String): double
+getDouble(Scanner, String,
double, double): double
ProductDB
+getProduct(String): Product
YG - CS170
64
The classes used by the Line Item application
 The Line Item application accepts a product code and quantity
from the user, creates a line item using that information, and
displays the result to the user.
 The Validator class is used to validate the data the user enters.
 The three instance variables of the LineItem class are used to store
a Product object, the quantity, and the line item total. The get and
set methods are used to get and set the values of these variables.
 The calculateTotal method of the LineItem class is used to
calculate the line item total, and the getFormattedTotal method is
used to format the total as a currency value.
YG - CS170
65
The LineItemApp class
import java.util.Scanner;
public class LineItemApp
{
public static void main(String args[])
{
// display a welcome message
System.out.println(
"Welcome to the Line Item Calculator");
System.out.println();
// create 1 or more line items
Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y"))
{
// get the input from the user
String productCode = Validator.getString(sc,
"Enter product code: ");
int quantity = Validator.getInt(sc,
"Enter quantity:
", 0, 1000);
YG - CS170
66
The LineItemApp class (continued)
// get the Product object
Product product =
ProductDB.getProduct(productCode);
// create the LineItem object
LineItem lineItem = new LineItem(product,
quantity);
// display the output
System.out.println();
System.out.println("LINE ITEM");
System.out.println("Code:
" +
product.getCode());
System.out.println("Description: " +
product.getDescription());
System.out.println("Price:
" +
product.getFormattedPrice());
System.out.println("Quantity:
" +
lineItem.getQuantity());
YG - CS170
67
The LineItemApp class (continued)
System.out.println("Total:
" +
lineItem.getFormattedTotal() + "\n");
// see if the user wants to continue
choice = Validator.getString(sc,
"Continue? (y/n): ");
System.out.println();
}
}
}
YG - CS170
68
The Validator class
import java.util.Scanner;
public class Validator
{
public static String getString(Scanner sc, String prompt)
{
System.out.print(prompt);
String s = sc.next(); // read the user entry
sc.nextLine();
// discard any other data entered on the line
return s;
}
YG - CS170
69
The Validator class (continued)
public static int getInt(Scanner sc, String prompt)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextInt())
{
i = sc.nextInt();
isValid = true;
}
else
{
System.out.println(
"Error! Invalid integer value. Try again.");
}
sc.nextLine();
// discard any other data entered on the line
}
return i;
}
YG - CS170
70
The Validator class (continued)
public static int getInt(Scanner sc, String prompt,
int min, int max)
{
int i = 0;
boolean isValid = false;
while (isValid == false)
{
i = getInt(sc, prompt);
if (i <= min)
System.out.println("Error!
Number must be greater than " + min + ".");
else if (i >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return i;
}
YG - CS170
71
The Validator class (continued)
public static double getDouble(Scanner sc, String prompt)
{
double d = 0;
boolean isValid = false;
while (isValid == false)
{
System.out.print(prompt);
if (sc.hasNextDouble())
{
d = sc.nextDouble();
isValid = true;
}
else
{
System.out.println(
"Error! Invalid decimal value. Try again.");
}
sc.nextLine();
// discard any other data entered on the line
}
return d;
}
YG - CS170
72
The Validator class (continued)
public static double getDouble(Scanner sc, String prompt,
double min, double max)
{
double d = 0;
boolean isValid = false;
while (isValid == false)
{
d = getDouble(sc, prompt);
if (d <= min)
System.out.println("Error!
Number must be greater than " + min + ".");
else if (d >= max)
System.out.println(
"Error! Number must be less than " + max + ".");
else
isValid = true;
}
return d;
}
}
YG - CS170
73
The LineItem class
import java.text.NumberFormat;
public class LineItem
{
private Product product;
private int quantity;
private double total;
public LineItem()
{
this.product = new Product();
this.quantity = 0;
this.total = 0;
}
public LineItem(Product product, int quantity)
{
this.product = product;
this.quantity = quantity;
}
YG - CS170
74
The LineItem class (continued)
public void setProduct(Product product)
{
this.product = product;
}
public Product getProduct()
{
return product;
}
public void setQuantity(int quantity)
{
this.quantity = quantity;
}
public int getQuantity()
{
return quantity;
}
YG - CS170
75
The LineItem class (continued)
public double getTotal()
{
this.calculateTotal();
return total;
}
private void calculateTotal()
{
total = quantity * product.getPrice();
}
public String getFormattedTotal()
{
NumberFormat currency =
NumberFormat.getCurrencyInstance();
return currency.format(this.getTotal());
}
}
YG - CS170
76