Building Java Programs Chapter 8 Classes Lecture 8

Building Java Programs Chapter 8: Classes Lecture 8 -1: Intro to Classes and Objects reading: 8. 1 - 8. 3 Copyright 2009 by Pearson Education

Need for Modularity Remember Homework 4? (Calorie Tracker) Age? (years) 25 Height? (inches) 65 Weight? (pounds) 120 Level of activity? (1 -5) 2 How can you write a method that would prompt for the users’ personal information and return those 4 values? Could use an array of size 4, but considered a hack – something that works but not for the right reasons (bad style!) Copyright 2009 by Pearson Education 2

Variations of Calorie Tracker What if we wanted to write other calorie tracking programs? The code written in Calorie. Tracker. java and BMICalculator. java will likely be useful Calorie. Tracker. java BMICalculator. java public static int compute. RMR(. . . ) public static int compute. BMI(. . . ) public static int round 2(. . . ) Calorie. Tracker. Pro. java public static int compute. BMI(. . . ) public static int compute. RMR(. . . ) public static int round 2(. . . ) Forced to redundantly copy and paste methods from program to program Copyright 2009 by Pearson Education 3

Classes as modules Would be nice to have a way to: Create our own data types “Personal. Info” type that contains person’s age, height, weight, and level of activity Reuse groups of methods (Making a Calorie. Tracking library with compute. BMI, compute. RMR, round 2 methods) module: A reusable piece of software. A class can serve as a module by containing common code. Example module classes: Math, Arrays, System Copyright 2009 by Pearson Education 4

Object-Oriented Programming Concepts reading: 8. 1 self-check: #1 -4 Copyright 2009 by Pearson Education

Clients of objects client program: A program that uses objects. Example: Circles is a client of Drawing. Panel and Graphics. Circles. java (client program) public class Circles { main(String[] args) { new Drawing. Panel(. . . ). . . } } Copyright 2009 by Pearson Education Drawing. Panel. java (class) public class Drawing. Panel {. . . } 6

Classes and objects class: A program entity that represents either: 1. A program / module, or 2. A template for a new type of objects. The Drawing. Panel class is a template for creating Drawing. Panel objects. object: An entity that combines state and behavior. object-oriented programming (OOP): Programs that perform their behavior as interactions between objects. Copyright 2009 by Pearson Education 7

Blueprint analogy Music player blueprint state: current song volume battery life behavior: power on/off change station/song change volume choose random song creates Music player #1 Music player #2 Music player #3 state: song = "Thriller" volume = 17 battery life = 2. 5 hrs state: song = "Octopus’s Garden" volume = 9 battery life = 3. 41 hrs state: song = "Flower in the Sun" volume = 24 battery life = 1. 8 hrs behavior: power on/off change station/song change volume choose random song Copyright 2009 by Pearson Education 8

Abstraction abstraction: A distancing between ideas and details. We can use objects without knowing how they work. abstraction in an i. Pod: You understand its external behavior (buttons, screen). You don't understand its inner details, and you don't need to. Copyright 2009 by Pearson Education 9

Our task In the following slides, we will implement a Point class as a way of learning about classes. We will define a type of objects named Point. Each Point object will contain x/y data called fields. Each Point object will contain behavior called methods. Client programs will use the Point objects. Copyright 2009 by Pearson Education 10

Object State: Fields reading: 8. 2 self-check: #5 -6 Copyright 2009 by Pearson Education 11

Point class, version 1 public class Point { int x; int y; } Save this code into a file named Point. java. The above code creates a new class named Point. Each Point object contains two pieces of data: an int named x, and an int named y. Point objects do not contain any behavior (yet). Copyright 2009 by Pearson Education 12

Fields field: A variable inside an object that is part of its state. Each object has its own copy of each field. Declaring a field, syntax: type name ; Example: public class Student { String name; // each Student object has a double gpa; // name and gpa data field } Copyright 2009 by Pearson Education 13

Accessing fields Other classes can access/modify an object's fields. access: modify: variable. field = value; Example: Point p 1 = new Point(); Point p 2 = new Point(); System. out. println("the x-coord is " + p 1. x); p 2. y = 13; Copyright 2009 by Pearson Education // access // modify 14

A class and its client Point. java is not, by itself, a runnable program. A class can be used by client programs. Point. Main. java (client program) public class Point. Main {. . . main(args) { Point p 1 = new Point(); p 1. x = 7; p 1. y = 2; Point p 2 = new Point(); p 2. x = 4; p 2. y = 3; . . . } } Copyright 2009 by Pearson Education Point. java (class of objects) public class Point { int x; int y; } x 7 y 2 x 4 y 3 15

Point client code The client code below (Point. Main. java) uses our Point class. public class Point. Main { public static void main(String[] args) { // create two Point objects Point p 1 = new Point(); p 1. y = 2; Point p 2 = new Point(); p 2. x = 4; System. out. println("p 1: (" + p 1. x + ", " + p 1. y + ")"); } } // move p 2 and then print it p 2. x += 2; p 2. y++; System. out. println("p 2: (" + p 2. x + ", " + p 2. y + ")"); OUTPUT: p 1: (0, 2) p 2: (6, 1) Copyright 2009 by Pearson Education 16
![More client code public class Point. Main 2 { public static void main(String[] args) More client code public class Point. Main 2 { public static void main(String[] args)](http://slidetodoc.com/presentation_image_h2/ae23ac56c096bd7ac12cb1a009d9575d/image-17.jpg)
More client code public class Point. Main 2 { public static void main(String[] args) { // create two Point objects Point p 1 = new Point(); p 1. x = 7; p 1. y = 2; Point p 2 = new Point(); p 2. x = 4; p 2. y = 3; System. out. println("p 1: (" + p 1. x + ", " + p 1. y + ")"); System. out. println("p 2: (" + p 2. x + ", " + p 2. y + ")"); // compute/print each point's distance double dist 1 = Math. sqrt(p 1. x * p 1. x + double dist 2 = Math. sqrt(p 2. x * p 2. x + System. out. println("p 1's distance from System. out. println("p 2's distance from the origin p 1. y * p 1. y); p 2. y * p 2. y); origin: " + dist 1); origin: " + dist 2); // move p 1 and p 2 and print them again p 1. x += 11; p 1. y += 6; p 2. x += 1; p 2. y += 7; System. out. println("p 1: (" + p 1. x + ", " + p 1. y + ")"); System. out. println("p 2: (" + p 2. x + ", " + p 2. y + ")"); } } // compute/print distance from p 1 to p 2 int dx = p 1. x - p 2. x; int dy = p 2. y - p 2. y; double distp 1 p 2 = Math. sqrt(dx * dx + dy * dy); System. out. println("distance from p 1 to p 2: " + distp 1 p 2); Copyright 2009 by Pearson Education 17

Object Behavior: Methods reading: 8. 3 self-check: #7 -9 exercises: #1 -4 Copyright 2009 by Pearson Education 18

Client code redundancy Our client program translated a Point object's location: // move p 2 and print it again p 2. x += 2; p 2. y += 4; System. out. println("p 2: (" + p 2. x + ", " + p 2. y + ")"); To translate several points, the code must be repeated: p 1. x += 11; p 1. y += 6; p 2. x += 2; p 2. y += 4; p 3. x += 1; p 3. y += 7; . . . Copyright 2009 by Pearson Education 19

Eliminating redundancy, v 1 We can eliminate the redundancy with a static method: // Shifts the location of the given point. public static void translate(Point p, int dx, int dy) { p. x += dx; p. y += dy; } main would call the method as follows: // move p 2 and then print it again translate(p 2, 2, 4); System. out. println("p 2: (" + p 2. x + ", " + p 2. y + ")"); (Why doesn't translate need to return the modified point? ) Copyright 2009 by Pearson Education 20

Problems with static solution The syntax doesn't match how we're used to using objects. translate(p 2, 2, 4); // ours (bad) If we wrote several client programs that translated Points, each would need a copy of the translate method. The point of classes is to combine state and behavior. translate behavior is closely related to a Point's data. The method belongs inside each Point object. p 2. translate(2, 4); Copyright 2009 by Pearson Education // Java's (better) 21

Instance methods instance method: One that exists inside each object of a class and defines behavior of that object. public type name(parameters) { statements; } same syntax as static methods, but without static keyword Example: public void shout() { System. out. println("HELLO THERE!"); } Copyright 2009 by Pearson Education 22

Instance method example public class Point { int x; int y; } // Changes the location of this Point object. public void translate(int dx, int dy) {. . . } The translate method no longer has a Point p parameter. How does the method know which point to move? Copyright 2009 by Pearson Education 23

Point object diagrams Each Point object has its own copy of the translate method, which operates on that object's state: Point p 1 = new Point(); p 1. x = 7; p 1. y = 2; Point p 2 = new Point(); p 2. x = 4; p 2. y = 3; p 1. translate(11, 6); p 2. translate(1, 7); p 2 Copyright 2009 by Pearson Education p 1 x 7 y 2 public void translate(int dx, int dy) { // this code can see p 1's x and y } x 4 y 3 public void translate(int dx, int dy) { // this code can see p 2's x and y } 24

The implicit parameter: The object on which an instance method is called. During the call p 1. translate(11, 6); , the object referred to by p 1 is the implicit parameter. During the call p 2. translate(1, 7); , the object referred to by p 2 is the implicit parameter. The instance method can refer to that object's fields. We say that it executes in the context of a particular object. translate can refer to the x and y of the object it was called on. Copyright 2009 by Pearson Education 25

Point class, version 2 public class Point { int x; int y; } // Changes the location of this Point object. public void translate(int dx, int dy) { x = x + dx; y = y + dy; } Now each Point object contains a method named translate that modifies its x and y fields by the given parameter values. Copyright 2009 by Pearson Education 26

Tracing method calls p 1. translate(11, 6); p 2. translate(1, 7); x p 1 Copyright 2009 by Pearson Education y 8 public void translate(int dx, int dy) { x = x + dx; y = y + dy; } x p 2 3 4 y 3 public void translate(int dx, int dy) { x = x + dx; y = y + dy; } 27
![Client code, version 2 public class Point. Main 2 { public static void main(String[] Client code, version 2 public class Point. Main 2 { public static void main(String[]](http://slidetodoc.com/presentation_image_h2/ae23ac56c096bd7ac12cb1a009d9575d/image-28.jpg)
Client code, version 2 public class Point. Main 2 { public static void main(String[] args) { // create two Point objects Point p 1 = new Point(); p 1. y = 2; Point p 2 = new Point(); p 2. x = 4; System. out. println("p 1: (" + p 1. x + ", " + p 1. y + ")"); } } // move p 2 and then print it p 2. translate(2, 1); System. out. println("p 2: (" + p 2. x + ", " + p 2. y + ")"); OUTPUT: p 1 is (0, 2) p 2 is (6, 1) Copyright 2009 by Pearson Education 28

Instance method questions Write a method distance. From. Origin that returns the distance between a Point and the origin, (0, 0). Use the following formula: Write a method distance that computes the distance between a Point and another Point parameter. Write a method set. Location that changes a Point's location to the (x, y) values passed. You may want to refactor the Point class to use this method. Modify the client code to use these methods. Copyright 2009 by Pearson Education 29

Client code question Recall our client program that produces this output: p 1: (7, 2) p 1's distance from origin: 7. 280109889280518 p 2: (4, 3) p 2's distance from origin: 5. 0 p 1: (18, 8) p 2: (5, 10) Modify this program to use our new methods. Copyright 2009 by Pearson Education 30

Client code answer // This client program uses the Point class. public class Point. Main { public static void main(String[] args) { // create two Point objects Point p 1 = new Point(); p 1. set. Location(7, 2); Point p 2 = new Point(); p 2. set. Location(4, 3); // print each point System. out. println("p 1: (" + p 1. x + ", " + p 1. y + ")"); System. out. println("p 2: (" + p 2. x + ", " + p 2. y + ")"); // compute/print each point's distance from the origin System. out. println("p 1's distance from origin: " + p 1. distance. From. Origin()); System. out. println("p 2's distance from origin: " + p 1. distance. From. Origin()); // move p 1 and p 2 and print them again p 1. translate(11, 6); p 2. translate(1, 7); System. out. println("p 1: (" + p 1. x + ", " + p 1. y + ")"); System. out. println("p 2: (" + p 2. x + ", " + p 2. y + ")"); } } // compute/print distance from p 1 to p 2 System. out. println("distance from p 1 to p 2: " + p 1. distance(p 2)); Copyright 2009 by Pearson Education 31
- Slides: 31