Chapter 07 Slides
Chapter 07 Slides
Chapter 7
How to code
classes
Knowledge
5. Describe the architecture commonly used for object-oriented programs.
6. Describe the concept of encapsulation and explain its importance to
object-oriented programming.
C7, Slide 2
Objectives (continued)
3. Differentiate between an object’s identity and its state.
4. Describe the basic components of a class.
5. Explain what an instance variable is.
6. Explain when a default constructor is used and what it does.
7. Explain what a copy constructor is and what it does.
8. Describe a signature of a constructor or method, and explain what
overloading means.
9. List four ways you can use the this keyword within a class
definition.
10. Explain the difference between how primitive types and reference
types are passed to a method.
11. Explain how static fields and static methods differ from instance
variables and instance methods.
C7, Slide 3
The architecture of a three-tiered application
C7, Slide 4
A class diagram for the Product class
C7, Slide 5
UML diagramming notes
UML (Unified Modeling Language) is the industry standard used
to model 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, and the plus sign
(+) marks the fields and methods that can be accessed by other
classes.
For each field, the diagram specifies the field name, a colon, and
the data type.
For each method, the diagram specifies the method name and a
set of parentheses. Within the parentheses, the diagram specifies
the data type for each parameter. After the parentheses, the
diagram specifies a colon and the data type for the return value.
C7, Slide 6
The relationship between a class and its objects
C7, Slide 7
The Product class (part 1)
import java.text.NumberFormat;
// the constructor
public Product() {
code = "";
description = "";
price = 0;
}
C7, Slide 8
The Product class (part 2)
// the set and get methods for the code variable
public void setCode(String code) {
this.code = code;
}
C7, Slide 9
The Product class (part 3)
// the set and get methods for the price
variable
public void setPrice(double price) {
this.price = price;
}
C7, Slide 10
The syntax for declaring instance variables
public|private primitiveType|ClassName variableName;
Examples
private double price;
private int quantity;
private String code;
private Product product;
C7, Slide 11
Where you can declare instance variables
public class Product {
C7, Slide 12
The syntax for coding constructors
public ClassName([parameterList]) {
// the statements of the constructor
}
C7, Slide 13
A constructor that assigns default values
public Product() {
code = null;
description = null;
price = 0.0;
}
C7, Slide 14
A constructor that assigns empty strings
instead of null values
public Product() {
code = "";
description = "";
price = 0.0;
}
C7, Slide 15
A custom constructor with three parameters
public Product(String code, String description,
double price) {
this.code = code;
this.description = description;
this.price = price;
}
C7, Slide 16
The syntax for coding a method
public|private returnType methodName([parameterList]) {
// the statements of the method
}
C7, Slide 17
A method that doesn’t accept parameters
or return data
public void printToConsole() {
System.out.println(code + "|" + description +
"|" + price);
}
C7, Slide 18
Get methods that return values
A string
public String getCode() {
return code;
}
A double value
public double getPrice() {
return price;
}
A formatted value
public String getPriceFormatted() {
NumberFormat currency =
NumberFormat.getCurrencyInstance();
return currency.format(price);
}
C7, Slide 19
A set method
public void setCode(String code) {
this.code = code;
}
C7, Slide 20
How to generate get and set methods
With NetBeans
Right-click the field name and select the
RefactorEncapsulate Fields command.
With Eclipse
Click on the field name and click the “Create getter and
setter” item.
C7, Slide 21
How to create an object and assign it to a variable
Syntax for creating an object
new ClassName([argumentList]);
Pass no arguments
Product product = new Product();
C7, Slide 22
How to call a method from an object
Syntax
object.methodName([argumentList])
Pass no arguments and return nothing
product.printToConsole();
C7, Slide 23
How to declare static fields
private static int objectCount = 0;
public static final int DAYS_IN_JANUARY = 31;
public static final float EARTH_MASS_IN_KG = 5.972e24F;
C7, Slide 24
A class that contains a static constant
and a static method
public class FinancialCalculations {
C7, Slide 25
How to call static fields
double monthlyAvg =
yearlyTotal / FinancialCalculations.MONTHS_IN_YEAR;
C7, Slide 26
The ProductDB class
public class ProductDB {
C7, Slide 27
The ProductDB class (continued)
else if (code.equalsIgnoreCase("mysql")) {
p.setDescription("Murach's MySQL");
p.setPrice(54.50);
}
else {
p.setDescription("Unknown");
}
return p;
}
}
C7, Slide 28
The console for the Product Viewer application
Welcome to the Product Viewer
SELECTED PRODUCT
Description: Murach's Java Programming
Price: $57.50
Continue? (y/n):
C7, Slide 29
The ProductApp class
import java.util.Scanner;
C7, Slide 30
The ProductApp class (continued)
// get the Product object
Product product =
ProductDB.getProduct(productCode);
C7, Slide 31
How assignment statements work
For primitive types
double p1 = 54.50;
double p2 = p1; // p1 and p2 store copies of 54.50
p2 = 57.50; // only changes p2
C7, Slide 32
How parameters work
For primitive types
public static double increasePrice(double price) {
// the price parameter is a copy of the double value
price = price * 1.1;
// does not change price in calling code
return price;
// returns changed price to calling code
}
C7, Slide 33
How method calls work
For primitive types
double price = 54.50;
price = increasePrice(price); // assignment necessary
C7, Slide 34
Code that makes a copy of a Product object
Product p1 = new Product("mysql", "Murach's MySQL",
54.50);
C7, Slide 35
The Product class with a copy constructor
public class Product {
public Product() {
code = "";
description = "";
price = 0;
}
C7, Slide 36
Code that uses the copy constructor
Product p1 = new Product("mysql", "Murach's MySQL",
54.50);
Product p2 = new Product(p1); // call copy constructor
C7, Slide 37
How to overload methods
A method that accepts one argument
public void printToConsole(String sep) {
System.out.println(
code + sep + description + sep + price);
}
C7, Slide 38
Code that calls the overloaded methods
Product product = new Product("java",
"Murach's Java Programming", 57.50);
p.printToConsole();
p.printToConsole(" ", true);
p.printToConsole(" ");
The console
java|Murach's Java Programming|57.5
java Murach's Java Programming 57.5
C7, Slide 39
How to refer to instance variables
of the current object
Syntax
this.variableName
C7, Slide 40
How to call a constructor of the current object
Syntax
this(argumentList);
C7, Slide 41
How to call a method of the current object
Syntax
this.methodName(argumentList)
C7, Slide 42
How to pass the current object to a method
Syntax
methodName(this)
C7, Slide 43
The console for the Line Item application
Welcome to the Line Item Calculator
LINE ITEM
Code: java
Description: Murach's Java Programming
Price: $57.50
Quantity: 2
Total: $115.00
Continue? (y/n):
C7, Slide 44
The class diagram for the Line Item application
C7, Slide 45
The LineItemApp class
public class LineItemApp {
C7, Slide 46
The LineItemApp class (continued)
// 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.getPriceFormatted());
System.out.println("Quantity: " +
lineItem.getQuantity());
System.out.println("Total: "
+ lineItem.getTotalFormatted() + "\n");
C7, Slide 47
The Console class (part 1)
import java.util.Scanner;
C7, Slide 48
The Console class (part 2)
public static int getInt(String prompt, int min, int max) {
while (true) {
int value = getInt(prompt);
if (value > min && value < max) {
return value;
} else {
System.out.println(
"Error! Number must be greater than "
+ min + " and less than " + max + ".");
}
}
}
C7, Slide 49
The Console class (part 3)
public static double getDouble(String prompt,
double min, double max) {
while (true) {
double value = getDouble(prompt);
if (value > min && value < max) {
return value;
} else {
System.out.println(
"Error! Number must be greater than "
+ min + " and less than " + max + ".");
}
}
}
C7, Slide 50
The LineItem class
import java.text.NumberFormat;
public LineItem() {
this.product = null;
this.quantity = 0;
}
C7, Slide 51
The LineItem class (continued)
public Product getProduct() {
return product;
}
C7, Slide 52