Top Banner
YG - CS170 1 C hapter6 How to define and use classes
76

Concept of Encapsulation

Jan 05, 2016

Download

Documents

annora

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 - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Concept of Encapsulation

YG - CS170 1

Chapter 6

How to define and use classes

Page 2: Concept of Encapsulation

YG - CS170 2

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.

Page 3: Concept of Encapsulation

YG - CS170 3

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.

Page 4: Concept of Encapsulation

YG - CS170 4

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.

Page 5: Concept of Encapsulation

YG - CS170 5

The architecture of a three-tiered application

Presentationclasses

Presentationlayer

Businessclasses

Middle layer

Databaseclasses

Database layer Database

Page 6: Concept of Encapsulation

YG - CS170 6

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.

Page 7: Concept of Encapsulation

YG - CS170 7

A class diagram for the Product class

Product

+setCode(String)+getCode(): String+setDescription(String)+getDescription(): String+setPrice(double)+getPrice(): double+getFormattedPrice(): String

-code: String-description: String-price: double

Fields

Methods

Page 8: Concept of Encapsulation

YG - CS170 8

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

Page 9: Concept of Encapsulation

YG - CS170 9

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 object-oriented 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.

Page 10: Concept of Encapsulation

YG - CS170 10

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.

Page 11: Concept of Encapsulation

YG - CS170 11

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

Page 12: Concept of Encapsulation

YG - CS170 12

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.

Page 13: Concept of Encapsulation

YG - CS170 13

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();

Page 14: Concept of Encapsulation

YG - CS170 14

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; }

Page 15: Concept of Encapsulation

YG - CS170 15

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; }

Page 16: Concept of Encapsulation

YG - CS170 16

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); } }

Page 17: Concept of Encapsulation

YG - CS170 17

The syntax for declaring instance variables public|private primitiveType|ClassName variableName;

Examples private double price; private int quantity; private String code; private Product product;

Page 18: Concept of Encapsulation

YG - CS170 18

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; }

Page 19: Concept of Encapsulation

YG - CS170 19

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.

Page 20: Concept of Encapsulation

YG - CS170 20

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; }

Page 21: Concept of Encapsulation

YG - CS170 21

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; }

Page 22: Concept of Encapsulation

YG - CS170 22

A constructor with one parameter public Product(String code) { this.code = code; Product p = ProductDB.getProduct(code); description = p.getDescription(); price = p.getPrice(); }

Page 23: Concept of Encapsulation

YG - CS170 23

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();

Page 24: Concept of Encapsulation

YG - CS170 24

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.

Page 25: Concept of Encapsulation

YG - CS170 25

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; }

Page 26: Concept of Encapsulation

YG - CS170 26

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); }

• 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

get methods

Page 27: Concept of Encapsulation

YG - CS170 27

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; }

• 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

set methods

Page 28: Concept of Encapsulation

YG - CS170 28

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.

Page 29: Concept of Encapsulation

YG - CS170 29

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); }

Page 30: Concept of Encapsulation

YG - CS170 30

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(); }

Page 31: Concept of Encapsulation

YG - CS170 31

Code that calls the PrintToConsole methods Product p = ProductDB.getProduct("java"); p.printToConsole(); p.printToConsole(" ", true); p.printToConsole(" ");

The console java|Murach's Beginning Java 2|49.5 java Murach's Beginning Java 2 49.5 java Murach's Beginning Java 2 49.5

Page 32: Concept of Encapsulation

YG - CS170 32

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

Page 33: Concept of Encapsulation

YG - CS170 33

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); }

Page 34: Concept of Encapsulation

YG - CS170 34

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); }

Page 35: Concept of Encapsulation

YG - CS170 35

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.

Page 36: Concept of Encapsulation

YG - CS170 36

How to create an object in two statements ClassName variableName; variableName = new ClassName(argumentList);

Example with no arguments Product product; product = new Product();

Page 37: Concept of Encapsulation

YG - CS170 37

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);

Page 38: Concept of Encapsulation

YG - CS170 38

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.

Page 39: Concept of Encapsulation

YG - CS170 39

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();

Page 40: Concept of Encapsulation

YG - CS170 40

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:";

Page 41: Concept of Encapsulation

YG - CS170 41

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.

Page 42: Concept of Encapsulation

YG - CS170 42

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

Page 43: Concept of Encapsulation

YG - CS170 43

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

Page 44: Concept of Encapsulation

YG - CS170 44

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.

Page 45: Concept of Encapsulation

YG - CS170 45

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); }

Page 46: Concept of Encapsulation

YG - CS170 46

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; } }

Page 47: Concept of Encapsulation

YG - CS170 47

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):

Page 48: Concept of Encapsulation

YG - CS170 48

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")) {

Page 49: Concept of Encapsulation

YG - CS170 49

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();

Page 50: Concept of Encapsulation

YG - CS170 50

The ProductApp class (continued) // see if the user wants to continue System.out.print("Continue? (y/n): "); choice = sc.nextLine(); System.out.println(); } } }

Page 51: Concept of Encapsulation

YG - CS170 51

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

Page 52: Concept of Encapsulation

YG - CS170 52

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;

Page 53: Concept of Encapsulation

YG - CS170 53

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; } }

Page 54: Concept of Encapsulation

YG - CS170 54

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; } ...

Page 55: Concept of Encapsulation

YG - CS170 55

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.

Page 56: Concept of Encapsulation

YG - CS170 56

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

Page 57: Concept of Encapsulation

YG - CS170 57

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

Page 58: Concept of Encapsulation

YG - CS170 58

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.

Page 59: Concept of Encapsulation

YG - CS170 59

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

Page 60: Concept of Encapsulation

YG - CS170 60

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); }

Page 61: Concept of Encapsulation

YG - CS170 61

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){} }

Page 62: Concept of Encapsulation

YG - CS170 62

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.

Page 63: Concept of Encapsulation

YG - CS170 63

The console for the Line Item application Welcome to the Line Item Calculator Enter product code: java Enter quantity: 2 LINE ITEM Code: java Description: Murach's Beginning Java 2 Price: $49.50 Quantity: 2 Total: $99.00 Continue? (y/n):

Page 64: Concept of Encapsulation

YG - CS170 64

The class diagrams

Product

+setCode(String)+getCode(): String+setDescription(String)+getDescription(): String+setPrice(double)+getPrice(): double+getFormattedPrice(): String

-code: String-description: String-price: double

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

LineItem

+setProduct(Product)+getProduct(): Product+setQuantity(int)+getQuantity(): int+getTotal(): double-calculateTotal()+getFormattedTotal(): String

-product: Product-quantity: int-total: double

Page 65: Concept of Encapsulation

YG - CS170 65

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.

Page 66: Concept of Encapsulation

YG - CS170 66

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);

Page 67: Concept of Encapsulation

YG - CS170 67

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());

Page 68: Concept of Encapsulation

YG - CS170 68

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(); } } }

Page 69: Concept of Encapsulation

YG - CS170 69

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; }

Page 70: Concept of Encapsulation

YG - CS170 70

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; }

Page 71: Concept of Encapsulation

YG - CS170 71

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; }

Page 72: Concept of Encapsulation

YG - CS170 72

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; }

Page 73: Concept of Encapsulation

YG - CS170 73

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; } }

Page 74: Concept of Encapsulation

YG - CS170 74

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; }

Page 75: Concept of Encapsulation

YG - CS170 75

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; }

Page 76: Concept of Encapsulation

YG - CS170 76

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()); } }