0% found this document useful (0 votes)
1 views

Chapter 07 Slides

Chapter 7 of Murach’s Java Programming focuses on coding classes, including instance variables, constructors, and methods. It covers object creation, encapsulation, and the architecture of object-oriented programs, along with practical examples like the Product class and its methods. The chapter also explains concepts like static fields, method overloading, and how to use the 'this' keyword within class definitions.

Uploaded by

kenjo138
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Chapter 07 Slides

Chapter 7 of Murach’s Java Programming focuses on coding classes, including instance variables, constructors, and methods. It covers object creation, encapsulation, and the architecture of object-oriented programs, along with practical examples like the Product class and its methods. The chapter also explains concepts like static fields, method overloading, and how to use the 'this' keyword within class definitions.

Uploaded by

kenjo138
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Murach’s Java Programming (6th Edition)

Chapter 7

How to code
classes

© 2022, Mike Murach & Associates, Inc. C7, Slide 1


Objectives
Applied
1. Code the instance variables, constructors, and methods of a class that
defines an object.
2. Write code that creates objects from a user-defined class and then uses the
methods of the objects to accomplish the required tasks.
3. Code a class that contains static fields and methods, and call these fields
and methods from other classes.
4. 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.

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;

public class Product {

// the instance variables


private String code;
private String description;
private double price;

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

public String getCode() {


return code;
}

// the set and get methods for the description


// variable
public void setDescription(String description) {
this.description = description;
}

public String getDescription() {


return description;
}

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

public double getPrice() {


return price;
}

// a custom get method for the price variable


public String getPriceFormatted() {
NumberFormat currency =
NumberFormat.getCurrencyInstance();
return currency.format(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 {

// 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 getPriceFormatted(){
return formattedPrice; }

// also possible to code instance variables here


private int test;
}

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

Another way to code this constructor


public Product(String c, String d, double p) {
code = c;
description = d;
price = p;
}

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

Another way to code a set method


public void setCode(String productCode) {
code = productCode;
}

C7, Slide 20
How to generate get and set methods
With NetBeans
 Right-click the field name and select the
RefactorEncapsulate 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();

Pass literal values as arguments


Product product = new Product(
"java", "Murach's Java Programming", 57.50);

Pass variables as arguments


Product product = new Product(code, description, price);

C7, Slide 22
How to call a method from an object
Syntax
object.methodName([argumentList])
Pass no arguments and return nothing
product.printToConsole();

Pass one argument and return nothing


product.setCode("mysql");

Pass no arguments and return a double value


double price = product.getPrice();

Pass no arguments and return a String object


String formattedPrice = product.getPriceFormatted();

An expression that includes a method call


System.out.println("Code: " +
product.getCode() + "\n\n" +
"Press Enter to continue or enter 'x' to exit:");

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 {

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

C7, Slide 25
How to call static fields
double monthlyAvg =
yearlyTotal / FinancialCalculations.MONTHS_IN_YEAR;

How to call static methods


double futureValue =
FinancialCalculations.calculateFutureValue(
100.0, 3.0, 3);

C7, Slide 26
The ProductDB class
public class ProductDB {

public static Product getProduct(String code) {


// create the Product object
Product p = new Product();

// fill the Product object with data


p.setCode(code);
if (code.equalsIgnoreCase("java")) {
p.setDescription("Murach's Java Programming");
p.setPrice(57.50);
}
else if (code.equalsIgnoreCase("jsp")) {
p.setDescription(
"Murach's Java Servlets and JSP");
p.setPrice(57.50);
}

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

Enter product code: java

SELECTED PRODUCT
Description: Murach's Java Programming
Price: $57.50

Continue? (y/n):

C7, Slide 29
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 Viewer");
System.out.println();

// display 1 or more products


Scanner sc = new Scanner(System.in);
String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
System.out.print("Enter product code: ");
String productCode = sc.nextLine();

C7, Slide 30
The ProductApp class (continued)
// 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.getPriceFormatted());
System.out.println();

// see if the user wants to continue


System.out.print("Continue? (y/n): ");
choice = sc.nextLine();
System.out.println();
}
}
}

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

For reference types


Product p1 = new Product("mysql", "Murach's MySQL",
54.50);
Product p2 = p1; // p1 and p2 refer to the same object
p2.setPrice(57.50); // changes p1 and 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
}

For reference types


public static void increasePrice(Product product) {
// the product parameter refers to the Product object
double price = product.getPrice() * 1.1;
product.setPrice(price);
// changes price in calling code
}

C7, Slide 33
How method calls work
For primitive types
double price = 54.50;
price = increasePrice(price); // assignment necessary

For reference types


Product product = new Product();
product.setPrice(54.50);
increasePrice(product); // assignment not necessary

C7, Slide 34
Code that makes a copy of a Product object
Product p1 = new Product("mysql", "Murach's MySQL",
54.50);

// use p1 object to set values of p2 object


Product p2 = new Product();
p2.setCode(p1.getCode());
p2.setDescription(p1.getDescription());
p2.setPrice(p2.getPrice());

p2.setPrice(57.50); // only changes p2


System.out.println(p1.getPrice()); // prints 54.50

C7, Slide 35
The Product class with a copy constructor
public class Product {

private String code;


private String description;
private double price;

public Product() {
code = "";
description = "";
price = 0;
}

// use parameter p to set values of new Product object


public Product(Product p) {
code = p.code;
description = p.description;
price = p.price;
}
...
}

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

p2.setPrice(57.50); // only changes p2


System.out.println(p1.getPrice()); // prints 54.50

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

An overloaded method that provides a default value


public void printToConsole() {
printToConsole("|"); // call first method
}

An overloaded method with two arguments


public void printToConsole(String sep,
boolean blankLineAfter) {
printToConsole(sep); // call first method
if (blankLineAfter) {
System.out.println();
}
}

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

java Murach's Java Programming 57.5

C7, Slide 39
How to refer to instance variables
of the current object
Syntax
this.variableName

A constructor that refers to three instance variables


public Product(String code, String description,
double price) {
this.code = code;
this.description = description;
this.price = price;
}

C7, Slide 40
How to call a constructor of the current object
Syntax
this(argumentList);

A constructor that calls another constructor


of the current object
public Product() {
this("", "", 0.0);
}

C7, Slide 41
How to call a method of the current object
Syntax
this.methodName(argumentList)

A method that calls another method of the current object


public String getPriceFormatted() {
NumberFormat currency =
NumberFormat.getCurrencyInstance();
return currency.format(this.getPrice());
}

C7, Slide 42
How to pass the current object to a method
Syntax
methodName(this)

A method that passes the current object


to another method
public void print() {
System.out.println(this);
}

C7, Slide 43
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 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 {

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


String choice = "y";
while (choice.equalsIgnoreCase("y")) {
// get the input from the user
String productCode = Console.getString(
"Enter product code: ");
int quantity = Console.getInt(
"Enter quantity: ", 0, 1000);

// get the Product object


Product product = ProductDB.getProduct(productCode);

// create the LineItem object


LineItem lineItem = new LineItem(product, quantity);

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

// see if the user wants to continue


choice = Console.getString("Continue? (y/n): ");
System.out.println();
}
}
}

C7, Slide 47
The Console class (part 1)
import java.util.Scanner;

public class Console {

private static Scanner sc = new Scanner(System.in);

public static String getString(String prompt) {


System.out.print(prompt);
return sc.nextLine();
}

public static int getInt(String prompt) {


while (true) {
System.out.print(prompt);
try {
return Integer.parseInt(sc.nextLine());
} catch(NumberFormatException e) {
System.out.println(
"Error! Invalid integer value.");
}
}
}

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 + ".");
}
}
}

public static double getDouble(String prompt) {


while (true) {
System.out.print(prompt);
try {
return Double.parseDouble(sc.nextLine());
} catch(NumberFormatException e) {
System.out.println("Error! Invalid integer value.");
}
}
}

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 class LineItem {

private Product product;


private int quantity;

public LineItem() {
this.product = null;
this.quantity = 0;
}

public LineItem(Product product, int quantity) {


this.product = product;
this.quantity = quantity;
}

public void setProduct(Product product) {


this.product = product;
}

C7, Slide 51
The LineItem class (continued)
public Product getProduct() {
return product;
}

public void setQuantity(int quantity) {


this.quantity = quantity;
}

public int getQuantity() {


return quantity;
}

public double getTotal() {


double total = product.getPrice() * quantity;
return total;
}

public String getTotalFormatted() {


NumberFormat currency
= NumberFormat.getCurrencyInstance();
return currency.format(this.getTotal());
}
}

C7, Slide 52

You might also like