Ifi7184 lesson7

129
IFI7184.DT – Lesson 7 2015 @ Sonia Sousa 1

Transcript of Ifi7184 lesson7

Page 1: Ifi7184 lesson7

@ Sonia Sousa 1

IFI7184.DT – Lesson 7

2015

Page 2: Ifi7184 lesson7

@ Sonia Sousa 2

Lesson 7 - Outline

2015

Method DesignCreating Objects

Loop statements

Identifying Classes and ObjectsEnumerated Types

Static Variables and MethodsWrapper Classes

Class Relationshipsextra

Page 3: Ifi7184 lesson7

@ Sonia Sousa 3

Program Development

• The creation of software involves four basic activities:

– establishing the requirements

– creating a design

– implementing the code

– testing the implementation

• These activities are not strictly linear – they overlap and interact

2015

Page 4: Ifi7184 lesson7

@ Sonia Sousa 4

Requirements

• Software requirements specify the tasks that a program must accomplish

– what to do, not how to do it

• Often an initial set of requirements is provided, but they should be critiqued and expanded

• It is difficult to establish detailed, unambiguous, and complete requirements

• Careful attention to the requirements can save significant time and expense in the overall project

2015

Page 5: Ifi7184 lesson7

@ Sonia Sousa 5

Design

• A software design specifies how a program will accomplish its requirements

• A software design specifies how the solution can be broken down into manageable pieces and what each piece will do

• An object-oriented design determines which classes and objects are needed, and specifies how they will interact

• Low level design details include how individual methods will accomplish their tasks

2015

Page 6: Ifi7184 lesson7

@ Sonia Sousa 6

Implementation

• Implementation is the process of translating a design into source code

• Novice programmers often think that writing code is the heart of software development, but actually it should be the least creative step

• Almost all important decisions are made during requirements and design stages

• Implementation should focus on coding details, including style guidelines and documentation

2015

Page 7: Ifi7184 lesson7

@ Sonia Sousa 7

Testing

• Testing attempts to ensure that the program will solve the intended problem under all the constraints specified in the requirements

• A program should be thoroughly tested with the goal of finding errors

• Debugging is the process of determining the cause of a problem and fixing it

• We revisit the details of the testing process later in this chapter

2015

Page 8: Ifi7184 lesson7

@ Sonia Sousa 8

Lesson 7 - Outline

2015

Method DesignCreating Objects

Loop statements

Identifying Classes and ObjectsEnumerated Types

Static Variables and MethodsWrapper Classes

Class Relationshipsextra

Page 9: Ifi7184 lesson7

@ Sonia Sousa 9

Anatomy of a Class

Creating Students objects

2015

Page 10: Ifi7184 lesson7

@ Sonia Sousa 10

Classes (Student, StudentCompare)

• Write a class that compares the grades of two students and tells who is the best

• Classes Student and main class StudentCompare

• The Student class contains two data values• a String name that represents the student's name

• an double grade that represents the student’s grade

– Write a Student constructor to set the name and the initial grade

2015

Page 11: Ifi7184 lesson7

@ Sonia Sousa 11

Creating Objects

• An object has:– state (attributes)

– String name

– double grade

• descriptive characteristics

– behaviors (what he can do)

– compareStudents

StudentCompare

NameGrade

compareStudents

Student

2015

Page 12: Ifi7184 lesson7

@ Sonia Sousa 12

Data scope

• The scope of data is the area in a program in which that data can be referenced (used)– Data declared at the class level can be

referenced by all methods in that class– Data declared within a method can be used

only in that method– Data declared within a method is called local

data

2015

Page 13: Ifi7184 lesson7

@ Sonia Sousa 13

Instance Data• A variable declared at the class level (such as name)

– is called class attribute or instance variable

• Each instance (object) has its own instance variable

– A class declares the type of the data, but it does not reserve memory space for it

• Each time a Student object is created,

– a new name variable is created as well

• The objects of a class share the method definitions,

– but each object has its own data space

• That's the only way two objects can have different states

2015

Page 14: Ifi7184 lesson7

@ Sonia Sousa

// Student.java Author: Sónia Sousa// Demonstrates the creation and use of a user-defined class.

public class Student {private String name;

private double grade;

public Student(String name, double grade) {this.name = name;this.grade = grade;

} public static void compareStudents(Student st1, Student st2) { if (st1.grade > st2.grade) { System.out.print(st1.name +" is a better student");} else { if (st2.grade > st1.grade) {System.out.print(st2.name +" is a better student");} else {System.out.println(st1.name+ " and " + st2.name+ " are on the same level");} } }

continue 142015

Page 15: Ifi7184 lesson7

@ Sonia Sousa 15

package studentManager;import java.util.Scanner;

public class StudentCompare {public static void main(String[] args) {

Student st1, st2, st3; String name; double grade;

Scanner scan = new Scanner(System.in);System.out.println("Insert the first name for Student

1");name = scan.next();System.out.println("Insert the grade for Student 1");

grade = scan.nextDouble();st1 = new Student(name,grade);System.out.println("Insert the first name for Student

2");name = scan.next();System.out.println("Insert the grade for Student 2");grade = scan.nextDouble();st2 = new Student(name,grade);Student.compareStudents(st1, st2);

}

continue

2015

Page 16: Ifi7184 lesson7

@ Sonia Sousa 16

Instance Data

• We can depict the two Student objects from the Student program as follows:

st1 Johnname

st2 Maryname

Each object maintains its own name variable, and thus its own state

2015

Page 17: Ifi7184 lesson7

@ Sonia Sousa 17

Quick Check

• Why was the grade variable declared as private in the Student class?– By making it private, each Student object

controls its own data and allows it to be modified only by the well-defined operations it provides.

2015

Page 18: Ifi7184 lesson7

@ Sonia Sousa 18

Classes

• The values of the data define the state of an object created from the class

• The functionality of the methods define the behaviors of the object

• For our Die class, we might declare an integer called faceValue that represents the current value showing on the face

• One of the methods would “roll” the die by setting faceValue to a random number between one and six

2015

Page 19: Ifi7184 lesson7

@ Sonia Sousa 19

Anatomy of a Class

Creating Die objects

2015

Page 20: Ifi7184 lesson7

@ Sonia Sousa 20

Classes (Die,RollingDice)

• Write a class that creates two six-sided Die objects, both with an initial face value of one.– Rolls both dice and returns the combined

result.– Returns the current combined dice total.– Returns the current value of the first die.– Returns the current value of the second die.

2015

Page 21: Ifi7184 lesson7

@ Sonia Sousa 21

Creating Objects

• An object has:– state (attributes)

• constant MAX that represents the maximum face value

int MAX = 6

• integer faceValue that represents the current face value

int faceValue = 1

– behaviors (what he can do)• Rolls the die and returns the result.

– The roll method uses the random method of the Math class to determine a new face value

faceValue = (int) (Math.random() * MAX) + 1;2015

Page 22: Ifi7184 lesson7

@ Sonia Sousa 22

Constructors

• As mentioned previously, a constructor is used to set up an object when it is initially created

• A constructor has the same name as the class

• The Die constructor is used to set the initial face value of each new die object to one

2015

Page 23: Ifi7184 lesson7

@ Sonia Sousa 23

//Die.java Author: Sonia Sousa//Represents one die (singular of dice) with faces showing values//between 1 and 6.

public class Die{private final int MAX = 6; // maximum face valueprivate int faceValue = 1; // current value showing on the die

// Constructor: sets the initial face value.

public Die(int faceValue) {this.faceValue = faceValue;

}

// Rolls the die and returns the result.public int roll(){ faceValue = (int) (Math.random() * MAX) + 1;

return faceValue;}

}continue

2015

Page 24: Ifi7184 lesson7

@ Sonia Sousa 24

continue

public class RollingDice2 {

public static void main(String[] args) {

// Creates two six-sided Die objects, both with an initial// face value of one.

int faceValue = 1;

Die die1 = new Die(faceValue);Die die2 = new Die(faceValue);

System.out.println (die1.roll()); System.out.println (die2.roll());

System.out.println ("Total: " + (die1.roll() +

die2.roll()));

}}

2015

Page 25: Ifi7184 lesson7

@ Sonia Sousa 25

Instance Data

• We can depict the two Die objects from the RollingDice program as follows:

die1 5faceValue

die2 2faceValue

Each object maintains its own faceValue variable, and thus its own state

2015

Page 26: Ifi7184 lesson7

@ Sonia Sousa 26

Quick Check

Where is instance data declared?

What is the scope of instance data?

What is local data?

At the class level.

It can be referenced in any method of the class.

Local data is declared within a method, and is only accessible in that method.

2015

Page 27: Ifi7184 lesson7

@ Sonia Sousa 27

Anatomy of a Class

Additional examples

2015

Page 28: Ifi7184 lesson7

@ Sonia Sousa 28

Lesson 7 - Outline

2015

Method DesignCreating Objects

Loop statements

Identifying Classes and ObjectsEnumerated Types

Static Variables and MethodsWrapper Classes

Class Relationshipsextra

Page 29: Ifi7184 lesson7

@ Sonia Sousa 29

The for Statement

• A for statement has the following syntax:

for ( initialization ; condition ; increment ) statement;

The initializationis executed once

before the loop begins

The statement isexecuted until the

condition becomes false

The increment portion is executed at the end of each

iteration

2015

Page 30: Ifi7184 lesson7

@ Sonia Sousa 30

Logic of a for loop

statement

true

conditionevaluated

false

increment

initialization

2015

Page 31: Ifi7184 lesson7

@ Sonia Sousa 31

The for Statement

• A for loop is functionally equivalent to the following while loop structure:

initialization;while ( condition ){ statement; increment;}

2015

Page 32: Ifi7184 lesson7

@ Sonia Sousa 32

The for Statement

• The initialization section can be used to declare a variablefor (int count=1; count <= 5; count++)

System.out.println (count);

• Like a while loop, the condition of a for loop is tested prior to executing the loop body

• Therefore, the body of a for loop will execute zero or more times

2015

Page 33: Ifi7184 lesson7

33

The for Statement

• The increment section can perform any calculation:for (int num=100; num > 0; num -= 5)

System.out.println (num);

• A for loop is well suited for executing statements a specific number of times that can be calculated or determined in advance

• See ForLoop.java

• See Multiples.java

• See Stars.java

@ Sonia Sousa 2015

Page 34: Ifi7184 lesson7

@ Sonia Sousa 34

The For Statement

Demonstrating a for loop using an array of Strings

2015

Page 35: Ifi7184 lesson7

@ Sonia Sousa 35

Main class (ForLoop) package (loop)

• Start by creating the object array – with the days of the week

static private String[] weekDays= {"Monday", "Tuesday”, "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};

– Then print the results using a for iterate over an array

• For loop that iterate over an array to print the String[]for (int i = 0; i < weekDays.length; i++) {

System.out.println(weekDays[i]);}

for ( initialization ; condition ; increment ) statement;

2015

Page 36: Ifi7184 lesson7

@ Sonia Sousa 36

// ForLoop.java Author: Sónia Sousa

package loops;

public class repeatedLoop {

static private String[] weekDays= {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday",

"Saturday", "Sunday"};

public static void main(String[] args) {

// Demonstrates the use of a For loopfor (int i = 0; i < weekDays.length; i++) {

System.out.println(weekDays[i]);}

}

}

2015

Page 37: Ifi7184 lesson7

@ Sonia Sousa 37

The For Statement

Demonstrates the use of a for loop to print a sequence of numbers.

2015

Page 38: Ifi7184 lesson7

@ Sonia Sousa 38

Main class (Multiples) package (loop)

• Create a java application that – Prints multiples of a user-specified number up to a

user-specified limit.• Start by

– Scan a positive number and the upper limit and print them

• Do a for loop that– Print a specific number of values per line of output

2015

Page 39: Ifi7184 lesson7

@ Sonia Sousa 39

//********************************************************************// Multiples.java Author: Lewis/Loftus//// Demonstrates the use of a for loop.//********************************************************************

import java.util.Scanner;

public class Multiples{ //----------------------------------------------------------------- // Prints multiples of a user-specified number up to a user- // specified limit. //----------------------------------------------------------------- public static void main (String[] args) { final int PER_LINE = 5; int value, limit, mult, count = 0;

Scanner scan = new Scanner (System.in);

System.out.print ("Enter a positive value: "); value = scan.nextInt();

continue

2015

Page 40: Ifi7184 lesson7

@ Sonia Sousa 40

continue

System.out.print ("Enter an upper limit: "); limit = scan.nextInt();

System.out.println (); System.out.println ("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:");

for (mult = value; mult <= limit; mult += value) { System.out.print (mult + "\t");

// Print a specific number of values per line of output count++; if (count % PER_LINE == 0) System.out.println(); } }}

2015

Page 41: Ifi7184 lesson7

@ Sonia Sousa 41

continue

System.out.print ("Enter an upper limit: "); limit = scan.nextInt();

System.out.println (); System.out.println ("The multiples of " + value + " between " + value + " and " + limit + " (inclusive) are:");

for (mult = value; mult <= limit; mult += value) { System.out.print (mult + "\t");

// Print a specific number of values per line of output count++; if (count % PER_LINE == 0) System.out.println(); } }}

Sample RunEnter a positive value: 7Enter an upper limit: 400

The multiples of 7 between 7 and 400 (inclusive) are:7 14 21 28 3542 49 56 63 7077 84 91 98 105112 119 126 133 140147 154 161 168 175182 189 196 203 210217 224 231 238 245252 259 266 273 280287 294 301 308 315322 329 336 343 350357 364 371 378 385392 399

2015

Page 42: Ifi7184 lesson7

@ Sonia Sousa 42

The For Statement

Demonstrates the use of nested for loops.

2015

Page 43: Ifi7184 lesson7

@ Sonia Sousa 43

Main class (Stars) package (loop)

• Create a java application that – Prints a triangle shape using asterisk (star)

characters.• Start by

– Create and initialize MAX_ROWS variable to 10• Do a for loop that

– Print a specific number of values per line of output

2015

Page 44: Ifi7184 lesson7

@ Sonia Sousa 44

//********************************************************************// Stars.java Author: Lewis/Loftus//// Demonstrates the use of nested for loops.//********************************************************************

public class Stars{ //----------------------------------------------------------------- // Prints a triangle shape using asterisk (star) characters. //----------------------------------------------------------------- public static void main (String[] args) { final int MAX_ROWS = 10;

for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) System.out.print ("*");

System.out.println(); } }}

2015

Page 45: Ifi7184 lesson7

45@ Sonia Sousa

//********************************************************************// Stars.java Author: Lewis/Loftus//// Demonstrates the use of nested for loops.//********************************************************************

public class Stars{ //----------------------------------------------------------------- // Prints a triangle shape using asterisk (star) characters. //----------------------------------------------------------------- public static void main (String[] args) { final int MAX_ROWS = 10;

for (int row = 1; row <= MAX_ROWS; row++) { for (int star = 1; star <= row; star++) System.out.print ("*");

System.out.println(); } }}

Output*******************************************************

2015

Page 46: Ifi7184 lesson7

@ Sonia Sousa 46

Quick Check

• Write a code fragment that rolls a die 100 times and counts the number of times a 3 comes up.Die die = new Die();

int count = 0;

for (int num=1; num <= 100; num++)

if (die.roll() == 3)

count++;

Sytem.out.println (count);

2015

Page 47: Ifi7184 lesson7

@ Sonia Sousa 47

The for Statement

• Each expression in the header of a for loop is optional

• If the initialization is left out, no initialization is performed

• If the condition is left out, it is always considered to be true, and therefore creates an infinite loop

• If the increment is left out, no increment operation is performed

2015

Page 48: Ifi7184 lesson7

@ Sonia Sousa 48

Lesson 7 - Outline

2015

Method DesignCreating Objects

Loop statements

Identifying Classes and ObjectsEnumerated Types

Static Variables and MethodsWrapper Classes

Class Relationshipsextra

Page 49: Ifi7184 lesson7

@ Sonia Sousa 49

Identifying Classes and Objects• The core activity of object-oriented design is determining

– the classes and objects that will make up the solution

• Then identify – Classes may be part of a class library,

– Which classes we can reused from a previous project,

– Or, the one’s that will be newly written.

• One way to identify potential classes is to – identify the objects discussed in the requirements

• Objects are generally nouns, and

• The services that an object provides are generally verbs.

2015

Page 50: Ifi7184 lesson7

@ Sonia Sousa 50

Identifying Classes and Objects• A partial requirements document:

• Of course, not all nouns will correspond to a class or object in the final solution

The user must be allowed to specify each product byits primary characteristics, including its name andproduct number. If the bar code does not match theproduct, then an error should be generated to themessage window and entered into the error log. Thesummary report of all transactions must be structuredas specified in section 7.A.

2015

Page 51: Ifi7184 lesson7

@ Sonia Sousa 51

Identifying Classes and Objects

• Remember that a class represents a group (classification) of objects with the same behaviors

• Generally, classes that represent objects should

– Be given names that are singular nouns

• Examples: Coin, Student, Message

– A class represents the concept of one such object

• We are free to instantiate as many of each object as needed

2015

Page 52: Ifi7184 lesson7

@ Sonia Sousa 52

Identifying Classes and Objects

• Sometimes it is challenging to decide whether something should be represented as a class– For example, should an employee's address be

represented as a set of instance variables or as an Address object

• The more you examine the problem and its details the more clear these issues become

• When a class becomes too complex, – it often should be decomposed into multiple smaller classes

to distribute the responsibilities

2015

Page 53: Ifi7184 lesson7

@ Sonia Sousa 53

Identifying Classes and Objects

• We want to define classes with the proper amount of detail

– For example, it may be unnecessary to create separate classes for each type of appliance in a house

• It may be sufficient to define a more general Appliance class with appropriate instance data

• It all depends on the details of the problem being solved

2015

Page 54: Ifi7184 lesson7

@ Sonia Sousa 54

Identifying Classes and Objects

• Part of identifying the classes we need is the process of assigning responsibilities to each class

• Every activity that a program must accomplish must be represented by one or more methods in one or more classes

• We generally use verbs for the names of methods

• In early stages it is not necessary to determine every method of every class – begin with primary responsibilities and evolve the design

2015

Page 55: Ifi7184 lesson7

@ Sonia Sousa 55

Lesson 7 - Outline

2015

Method DesignCreating Objects

Loop statements

Identifying Classes and ObjectsEnumerated Types

Wrapper Classes

Static Variables and MethodsClass RelationshipsExtra

Page 56: Ifi7184 lesson7

@ Sonia Sousa 56

Enumerated Types• An enumerated type declaration

– lists all possible values for a variable of that type

– The values are identifiers of your own choosing

• The following declaration creates an enumerated type called Seasonenum Season {winter, spring, summer, fall};

• Any number of values can be listed

2015

Page 57: Ifi7184 lesson7

@ Sonia Sousa 57

Enumerated Types

• Once a type is defined,

– a variable of that type can be declared:

Season time;

• And it can be assigned a value:

time = Season.fall;

– The values are referenced through the name of the type

• Enumerated types are type-safe

– you cannot assign any value other than those listed

2015

Page 58: Ifi7184 lesson7

@ Sonia Sousa 58

Ordinal Values

• Internally, each value of an enumerated type is stored as an integer, – called its ordinal value

• The first value in an enumerated type– has an ordinal value of zero, the second one, and so on

• However, you cannot assign a numeric value to an enumerated type, – even if it corresponds to a valid ordinal value

2015

Page 59: Ifi7184 lesson7

@ Sonia Sousa 59

Enumerated Types

• The declaration of an enumerated type is a special type of class, and – each variable of that type is an object

– cone1.ordinal()• The ordinal method returns the ordinal value of the object

– cone1.name()• The name method returns the name of the identifier

corresponding to the object's value

• See IceCream.java

2015

Page 60: Ifi7184 lesson7

@ Sonia Sousa 60

Enumerated Types

Demonstrates the use of enumerated types

2015

Page 61: Ifi7184 lesson7

@ Sonia Sousa 61

//********************************************************************// IceCream.java Author: Lewis/Loftus//// Demonstrates the use of enumerated types.//********************************************************************

public class IceCream{ enum Flavor {vanilla, chocolate, strawberry, fudgeRipple, coffee, rockyRoad, mintChocolateChip, cookieDough}

//----------------------------------------------------------------- // Creates and uses variables of the Flavor type. //----------------------------------------------------------------- public static void main (String[] args) { Flavor cone1, cone2, cone3;

cone1 = Flavor.rockyRoad; cone2 = Flavor.chocolate;

System.out.println ("cone1 value: " + cone1); System.out.println ("cone1 ordinal: " + cone1.ordinal()); System.out.println ("cone1 name: " + cone1.name());

continued

2015

Page 62: Ifi7184 lesson7

@ Sonia Sousa 62

continued

System.out.println (); System.out.println ("cone2 value: " + cone2); System.out.println ("cone2 ordinal: " + cone2.ordinal()); System.out.println ("cone2 name: " + cone2.name());

cone3 = cone1;

System.out.println (); System.out.println ("cone3 value: " + cone3); System.out.println ("cone3 ordinal: " + cone3.ordinal()); System.out.println ("cone3 name: " + cone3.name()); }}

2015

Page 63: Ifi7184 lesson7

@ Sonia Sousa 63

continued

System.out.println (); System.out.println ("cone2 value: " + cone2); System.out.println ("cone2 ordinal: " + cone2.ordinal()); System.out.println ("cone2 name: " + cone2.name());

cone3 = cone1;

System.out.println (); System.out.println ("cone3 value: " + cone3); System.out.println ("cone3 ordinal: " + cone3.ordinal()); System.out.println ("cone3 name: " + cone3.name()); }}

Outputcone1 value: rockyRoadcone1 ordinal: 5cone1 name: rockyRoadcone2 value: chocolatecone2 ordinal: 1cone2 name: chocolatecone3 value: rockyRoadcone3 ordinal: 5cone3 name: rockyRoad

2015

Page 64: Ifi7184 lesson7

@ Sonia Sousa 64

Lesson 7 - Outline

2015

Method DesignCreating Objects

Loop statements

Identifying Classes and ObjectsEnumerated Types

Static Variables and MethodsWrapper Classes

Class RelationshipsExtra

Page 65: Ifi7184 lesson7

@ Sonia Sousa 65

Static Class Members

• Recall that a static method is one that can be invoked through its class name

• For example, the methods of the Math class are static:

result = Math.sqrt(25)

• Variables can be static as well

• Determining if a method or variable should be static is an important design decision

2015

Page 66: Ifi7184 lesson7

@ Sonia Sousa 66

The static Modifier• We declare static methods and variables using

the static modifier

• It associates the method or variable with the class rather than with an object of that class

• Static methods are sometimes called class methods and static variables are sometimes called class variables

• Let's carefully consider the implications of each

2015

Page 67: Ifi7184 lesson7

@ Sonia Sousa 67

Static Variables• Normally, each object has its own data space, but if a

variable is declared as static, only one copy of the variable exists

private static float price;

• Memory space for a static variable is created when the class is first referenced

• All objects instantiated from the class share its static variables

• Changing the value of a static variable in one object changes it for all others

2015

Page 68: Ifi7184 lesson7

@ Sonia Sousa 68

Static Methods

• Because it is declared as static, the cube method can be invoked through the class name:

value = Helper.cube(4);

public class Helper{ public static int cube (int num) { return num * num * num; }}

2015

Page 69: Ifi7184 lesson7

@ Sonia Sousa 69

Static Class Members

• The order of the modifiers can be interchanged, but by convention visibility modifiers come first

• Recall that the main method is static – it is invoked by the Java interpreter without creating an object

• Static methods cannot reference instance variables because instance variables don't exist until an object exists

• However, a static method can reference static variables or local variables

2015

Page 70: Ifi7184 lesson7

@ Sonia Sousa 70

Static Class Members

• Static methods and static variables often work together

• The following example keeps track of how many Slogan objects have been created using a static variable, and makes that information available using a static method

• See SloganCounter.java • See Slogan.java

2015

Page 71: Ifi7184 lesson7

@ Sonia Sousa 71

//********************************************************************// SloganCounter.java Author: Lewis/Loftus//// Demonstrates the use of the static modifier.//********************************************************************

public class SloganCounter{ //----------------------------------------------------------------- // Creates several Slogan objects and prints the number of // objects that were created. //----------------------------------------------------------------- public static void main (String[] args) { Slogan obj;

obj = new Slogan ("Remember the Alamo."); System.out.println (obj);

obj = new Slogan ("Don't Worry. Be Happy."); System.out.println (obj);

continue

2015

Page 72: Ifi7184 lesson7

@ Sonia Sousa 72

continue

obj = new Slogan ("Live Free or Die."); System.out.println (obj);

obj = new Slogan ("Talk is Cheap."); System.out.println (obj);

obj = new Slogan ("Write Once, Run Anywhere."); System.out.println (obj);

System.out.println(); System.out.println ("Slogans created: " + Slogan.getCount()); }}

2015

Page 73: Ifi7184 lesson7

@ Sonia Sousa 73

continue

obj = new Slogan ("Live Free or Die."); System.out.println (obj);

obj = new Slogan ("Talk is Cheap."); System.out.println (obj);

obj = new Slogan ("Write Once, Run Anywhere."); System.out.println (obj);

System.out.println(); System.out.println ("Slogans created: " + Slogan.getCount()); }}

OutputRemember the Alamo.Don't Worry. Be Happy.Live Free or Die.Talk is Cheap.Write Once, Run Anywhere.

Slogans created: 5

2015

Page 74: Ifi7184 lesson7

74@ Sonia Sousa

//********************************************************************// Slogan.java Author: Lewis/Loftus//// Represents a single slogan string.//********************************************************************

public class Slogan{ private String phrase; private static int count = 0;

//----------------------------------------------------------------- // Constructor: Sets up the slogan and counts the number of // instances created. //----------------------------------------------------------------- public Slogan (String str) { phrase = str; count++; }

continue

2015

Page 75: Ifi7184 lesson7

@ Sonia Sousa 75

continue

//----------------------------------------------------------------- // Returns this slogan as a string. //----------------------------------------------------------------- public String toString() { return phrase; }

//----------------------------------------------------------------- // Returns the number of instances of this class that have been // created. //----------------------------------------------------------------- public static int getCount () { return count; }}

2015

Page 76: Ifi7184 lesson7

@ Sonia Sousa 76

Quick Check• Why can't a static method reference an instance variable?

– Because instance data is created only when an– object is created.

– You don't need an object to execute a static method.

– And even if you had an object, which object's instance– data would be referenced? (remember, the method is– invoked through the class name)

2015

Page 77: Ifi7184 lesson7

@ Sonia Sousa 77

Lesson 7 - Outline

2015

Method DesignCreating Objects

Loop statements

Identifying Classes and ObjectsEnumerated Types

Static Variables and MethodsWrapper Classes

Class RelationshipsExtra

Page 78: Ifi7184 lesson7

@ Sonia Sousa 78

Wrapper Classes

Primitive Type Wrapper Classbyte Byte

short Shortint Integerlong Longfloat Floatdouble Doublechar Character

boolean Boolean

• The java.lang package contains wrapper classes that correspond to each primitive type:

2015

Page 79: Ifi7184 lesson7

@ Sonia Sousa 79

Wrapper Classes

• The following declaration creates an Integer object which represents the integer 40 as an object

Integer age = new Integer(40);

• An object of a wrapper class can be used in any situation where a primitive value will not suffice

• For example, some objects serve as containers of other objects

• Primitive values could not be stored in such containers, but wrapper objects could be

2015

Page 80: Ifi7184 lesson7

@ Sonia Sousa 80

Wrapper Classes

• Wrapper classes also contain static methods that help manage the associated type

• For example, the Integer class contains a method to convert an integer stored in a String to an int value:

num = Integer.parseInt(str);

• They often contain useful constants as well

• For example, the Integer class contains MIN_VALUE and MAX_VALUE which hold the smallest and largest int values

2015

Page 81: Ifi7184 lesson7

@ Sonia Sousa 81

Autoboxing

• Autoboxing is the automatic conversion of a primitive value to a corresponding wrapper object:

Integer obj;

int num = 42;

obj = num;

• The assignment creates the appropriate Integer object

• The reverse conversion (called unboxing) also occurs automatically as needed

2015

Page 82: Ifi7184 lesson7

@ Sonia Sousa 82

Quick Check

• Are the following assignments valid? Explain.Double value = 15.75;

Character ch = new Character('T');

char myChar = ch;

2015

Page 83: Ifi7184 lesson7

@ Sonia Sousa 83

Quick Check

• Are the following assignments valid? Explain.– Double value = 15.75;

• Yes. The double literal is autoboxed into a Double object.– Character ch = new Character('T');

• Yes, the char in the object is unboxed before the assignment.– char myChar = ch;

2015

Page 84: Ifi7184 lesson7

@ Sonia Sousa 84

Lesson 7 - Outline

2015

Method DesignCreating Objects

Loop statements

Identifying Classes and ObjectsEnumerated Types

Static Variables and MethodsWrapper Classes

Class RelationshipsExtra

Page 85: Ifi7184 lesson7

@ Sonia Sousa 85

Class Relationships

• Classes in a software system can have various types of relationships to each other

• Three of the most common relationships:– Dependency: A uses B– Aggregation: A has-a B– Inheritance: A is-a B

• Let's discuss dependency and aggregation further

2015

Page 86: Ifi7184 lesson7

@ Sonia Sousa 86

Dependency

• A dependency exists when one class relies on another in some way, usually by invoking the methods of the other

• We've seen dependencies in many previous examples

• We don't want numerous or complex dependencies among classes

• Nor do we want complex classes that don't depend on others

• A good design strikes the right balance

2015

Page 87: Ifi7184 lesson7

@ Sonia Sousa 87

Dependency

• Some dependencies occur between objects of the same class

• A method of the class may accept an object of the same class as a parameter

• For example, the concat method of the String class takes as a parameter another String object

str3 = str1.concat(str2);

2015

Page 88: Ifi7184 lesson7

@ Sonia Sousa 88

Dependency

• The following example defines a class called RationalNumber

• A rational number is a value that can be represented as the ratio of two integers

• Several methods of the RationalNumber class accept another RationalNumber object as a parameter

• See RationalTester.java

• See RationalNumber.java

2015

Page 89: Ifi7184 lesson7

@ Sonia Sousa 89

//********************************************************************// RationalTester.java Author: Lewis/Loftus//// Driver to exercise the use of multiple Rational objects.//********************************************************************

public class RationalTester{ //----------------------------------------------------------------- // Creates some rational number objects and performs various // operations on them. //----------------------------------------------------------------- public static void main (String[] args) { RationalNumber r1 = new RationalNumber (6, 8); RationalNumber r2 = new RationalNumber (1, 3); RationalNumber r3, r4, r5, r6, r7;

System.out.println ("First rational number: " + r1); System.out.println ("Second rational number: " + r2);

continue

2015

Page 90: Ifi7184 lesson7

@ Sonia Sousa 90

continue

if (r1.isLike(r2)) System.out.println ("r1 and r2 are equal."); else System.out.println ("r1 and r2 are NOT equal.");

r3 = r1.reciprocal(); System.out.println ("The reciprocal of r1 is: " + r3);

r4 = r1.add(r2); r5 = r1.subtract(r2); r6 = r1.multiply(r2); r7 = r1.divide(r2);

System.out.println ("r1 + r2: " + r4); System.out.println ("r1 - r2: " + r5); System.out.println ("r1 * r2: " + r6); System.out.println ("r1 / r2: " + r7); }}

2015

Page 91: Ifi7184 lesson7

@ Sonia Sousa 91

continue

if (r1.isLike(r2)) System.out.println ("r1 and r2 are equal."); else System.out.println ("r1 and r2 are NOT equal.");

r3 = r1.reciprocal(); System.out.println ("The reciprocal of r1 is: " + r3);

r4 = r1.add(r2); r5 = r1.subtract(r2); r6 = r1.multiply(r2); r7 = r1.divide(r2);

System.out.println ("r1 + r2: " + r4); System.out.println ("r1 - r2: " + r5); System.out.println ("r1 * r2: " + r6); System.out.println ("r1 / r2: " + r7); }}

OutputFirst rational number: 3/4Second rational number: 1/3r1 and r2 are NOT equal.The reciprocal of r1 is: 4/3r1 + r2: 13/12r1 - r2: 5/12r1 * r2: 1/4r1 / r2: 9/4

2015

Page 92: Ifi7184 lesson7

@ Sonia Sousa 92

//********************************************************************// RationalNumber.java Author: Lewis/Loftus//// Represents one rational number with a numerator and denominator.//********************************************************************

public class RationalNumber{ private int numerator, denominator;

//----------------------------------------------------------------- // Constructor: Sets up the rational number by ensuring a nonzero // denominator and making only the numerator signed. //----------------------------------------------------------------- public RationalNumber (int numer, int denom) { if (denom == 0) denom = 1;

// Make the numerator "store" the sign if (denom < 0) { numer = numer * -1; denom = denom * -1; }

continue

2015

Page 93: Ifi7184 lesson7

@ Sonia Sousa 93

continue

numerator = numer; denominator = denom;

reduce(); }

//----------------------------------------------------------------- // Returns the numerator of this rational number. //----------------------------------------------------------------- public int getNumerator () { return numerator; }

//----------------------------------------------------------------- // Returns the denominator of this rational number. //----------------------------------------------------------------- public int getDenominator () { return denominator; }

continue

2015

Page 94: Ifi7184 lesson7

@ Sonia Sousa 94

continue

//----------------------------------------------------------------- // Returns the reciprocal of this rational number. //----------------------------------------------------------------- public RationalNumber reciprocal () { return new RationalNumber (denominator, numerator); }

//----------------------------------------------------------------- // Adds this rational number to the one passed as a parameter. // A common denominator is found by multiplying the individual // denominators. //----------------------------------------------------------------- public RationalNumber add (RationalNumber op2) { int commonDenominator = denominator * op2.getDenominator(); int numerator1 = numerator * op2.getDenominator(); int numerator2 = op2.getNumerator() * denominator; int sum = numerator1 + numerator2;

return new RationalNumber (sum, commonDenominator); }

continue

2015

Page 95: Ifi7184 lesson7

@ Sonia Sousa 95

continue

//----------------------------------------------------------------- // Subtracts the rational number passed as a parameter from this // rational number. //----------------------------------------------------------------- public RationalNumber subtract (RationalNumber op2) { int commonDenominator = denominator * op2.getDenominator(); int numerator1 = numerator * op2.getDenominator(); int numerator2 = op2.getNumerator() * denominator; int difference = numerator1 - numerator2;

return new RationalNumber (difference, commonDenominator); }

//----------------------------------------------------------------- // Multiplies this rational number by the one passed as a // parameter. //----------------------------------------------------------------- public RationalNumber multiply (RationalNumber op2) { int numer = numerator * op2.getNumerator(); int denom = denominator * op2.getDenominator();

return new RationalNumber (numer, denom); }

continue2015

Page 96: Ifi7184 lesson7

@ Sonia Sousa 96

continue

//----------------------------------------------------------------- // Divides this rational number by the one passed as a parameter // by multiplying by the reciprocal of the second rational. //----------------------------------------------------------------- public RationalNumber divide (RationalNumber op2) { return multiply (op2.reciprocal()); }

//----------------------------------------------------------------- // Determines if this rational number is equal to the one passed // as a parameter. Assumes they are both reduced. //----------------------------------------------------------------- public boolean isLike (RationalNumber op2) { return ( numerator == op2.getNumerator() && denominator == op2.getDenominator() ); }

continue

2015

Page 97: Ifi7184 lesson7

@ Sonia Sousa 97

continue

//----------------------------------------------------------------- // Returns this rational number as a string. //----------------------------------------------------------------- public String toString () { String result; if (numerator == 0) result = "0"; else if (denominator == 1) result = numerator + ""; else result = numerator + "/" + denominator; return result; }

continue

2015

Page 98: Ifi7184 lesson7

@ Sonia Sousa 98

continue

//----------------------------------------------------------------- // Reduces this rational number by dividing both the numerator // and the denominator by their greatest common divisor. //----------------------------------------------------------------- private void reduce () { if (numerator != 0) { int common = gcd (Math.abs(numerator), denominator);

numerator = numerator / common; denominator = denominator / common; } }

continue

2015

Page 99: Ifi7184 lesson7

@ Sonia Sousa 99

continue

//----------------------------------------------------------------- // Computes and returns the greatest common divisor of the two // positive parameters. Uses Euclid's algorithm. //----------------------------------------------------------------- private int gcd (int num1, int num2) { while (num1 != num2) if (num1 > num2) num1 = num1 - num2; else num2 = num2 - num1;

return num1; }}

2015

Page 100: Ifi7184 lesson7

@ Sonia Sousa 100

Aggregation

• An aggregate is an object that is made up of other objects

• Therefore aggregation is a has-a relationship– A car has a chassis

• An aggregate object contains references to other objects as instance data

• This is a special kind of dependency; the aggregate relies on the objects that compose it

2015

Page 101: Ifi7184 lesson7

@ Sonia Sousa 101

Aggregation

• In the following example, a Student object is composed, in part, of Address objects

• A student has an address (in fact each student has two addresses)

• See StudentBody.java

• See Student.java

• See Address.java

2015

Page 102: Ifi7184 lesson7

@ Sonia Sousa 102

//********************************************************************// StudentBody.java Author: Lewis/Loftus//// Demonstrates the use of an aggregate class.//********************************************************************

public class StudentBody { //----------------------------------------------------------------- // Creates some Address and Student objects and prints them. //----------------------------------------------------------------- public static void main (String[] args) { Address school = new Address ("800 Lancaster Ave.", "Villanova", "PA", 19085); Address jHome = new Address ("21 Jump Street", "Lynchburg", "VA", 24551); Student john = new Student ("John", "Smith", jHome, school);

Address mHome = new Address ("123 Main Street", "Euclid", "OH", 44132); Student marsha = new Student ("Marsha", "Jones", mHome, school);

System.out.println (john); System.out.println (); System.out.println (marsha); }}

2015

Page 103: Ifi7184 lesson7

@ Sonia Sousa 103

//********************************************************************// StudentBody.java Author: Lewis/Loftus//// Demonstrates the use of an aggregate class.//********************************************************************

public class StudentBody { //----------------------------------------------------------------- // Creates some Address and Student objects and prints them. //----------------------------------------------------------------- public static void main (String[] args) { Address school = new Address ("800 Lancaster Ave.", "Villanova", "PA", 19085); Address jHome = new Address ("21 Jump Street", "Lynchburg", "VA", 24551); Student john = new Student ("John", "Smith", jHome, school);

Address mHome = new Address ("123 Main Street", "Euclid", "OH", 44132); Student marsha = new Student ("Marsha", "Jones", mHome, school);

System.out.println (john); System.out.println (); System.out.println (marsha); }}

OutputJohn SmithHome Address:21 Jump StreetLynchburg, VA 24551School Address:800 Lancaster Ave.Villanova, PA 19085

Marsha JonesHome Address:123 Main StreetEuclid, OH 44132School Address:800 Lancaster Ave.Villanova, PA 19085

2015

Page 104: Ifi7184 lesson7

@ Sonia Sousa 104

//********************************************************************// Student.java Author: Lewis/Loftus//// Represents a college student.//********************************************************************

public class Student{ private String firstName, lastName; private Address homeAddress, schoolAddress;

//----------------------------------------------------------------- // Constructor: Sets up this student with the specified values. //----------------------------------------------------------------- public Student (String first, String last, Address home, Address school) { firstName = first; lastName = last; homeAddress = home; schoolAddress = school; }

continue

2015

Page 105: Ifi7184 lesson7

@ Sonia Sousa 105

continue

//----------------------------------------------------------------- // Returns a string description of this Student object. //----------------------------------------------------------------- public String toString() { String result;

result = firstName + " " + lastName + "\n"; result += "Home Address:\n" + homeAddress + "\n"; result += "School Address:\n" + schoolAddress;

return result; }}

2015

Page 106: Ifi7184 lesson7

@ Sonia Sousa 106

//********************************************************************// Address.java Author: Lewis/Loftus//// Represents a street address.//********************************************************************

public class Address{ private String streetAddress, city, state; private long zipCode;

//----------------------------------------------------------------- // Constructor: Sets up this address with the specified data. //----------------------------------------------------------------- public Address (String street, String town, String st, long zip) { streetAddress = street; city = town; state = st; zipCode = zip; }

continue

2015

Page 107: Ifi7184 lesson7

@ Sonia Sousa 107

continue

//----------------------------------------------------------------- // Returns a description of this Address object. //----------------------------------------------------------------- public String toString() { String result;

result = streetAddress + "\n"; result += city + ", " + state + " " + zipCode;

return result; }}

2015

Page 108: Ifi7184 lesson7

@ Sonia Sousa 108

Aggregation in UMLStudentBody

+ main (args : String[]) : void

+ toString() : String

Student- firstName : String- lastName : String- homeAddress : Address- schoolAddress : Address

+ toString() : String

- streetAddress : String- city : String- state : String- zipCode : long

Address

2015

Page 109: Ifi7184 lesson7

@ Sonia Sousa 109

The this Reference

• The this reference allows an object to refer to itself

• That is, the this reference, used inside a method, refers to the object through which the method is being executed

• Suppose the this reference is used inside a method called tryMe, which is invoked as follows:

obj1.tryMe();

obj2.tryMe();

• In the first invocation, the this reference refers to obj1; in the second it refers to obj2

2015

Page 110: Ifi7184 lesson7

@ Sonia Sousa 110

The this reference• The this reference can be used to distinguish the

instance variables of a class from corresponding method parameters with the same names

• The constructor of the Account class from Chapter 4 could have been written as follows:

public Account (String name, long acctNumber, double balance){ this.name = name; this.acctNumber = acctNumber; this.balance = balance;}

2015

Page 111: Ifi7184 lesson7

@ Sonia Sousa 111

Lesson 7 - Outline

2015

Method DesignCreating Objects

Loop statements

Identifying Classes and ObjectsEnumerated Types

Static Variables and MethodsWrapper Classes

Class Relationshipsextra

Page 112: Ifi7184 lesson7

@ Sonia Sousa 112

Anatomy of a Class

Additional examples

2015

Page 113: Ifi7184 lesson7

@ Sonia Sousa 113

// StudentManager.java Author: Isaias Barreto da Rosa//// Demonstrates the creation and use of a user-defined class.

package studentmanager;import java.util.Scanner;public class StudentManager {

// Compares the grades of two students and tells who is the best static void compareStudents(Student st1, Student st2) { if (st1.getGrade() > st2.getGrade()) { System.out.print(st1.getName +" is a better student");} else { if (st2.getGrade() > st1.geGrade()) {System.out.print(st2.getName() +" is a better student");} else {System.out.println(st1.getNname() + " and " + st2.getName()

+ "are on the same level");} } }

2015

continue

Page 114: Ifi7184 lesson7

@ Sonia Sousa 114

Continue

public static void main(String[] args) { Student st1, st2, st3; String name; double grade; Scanner scan = new Scanner(System.in); System.out.println("Insert the first name for Student 1"); name = scan.nextLine(); System.out.println("Insert the grade for Student 1"); grade = scan.nextDouble(); st1 = new Student(name,grade); System.out.println("Insert the first name for Student 2"); name = scan.nextLine(); System.out.println("Insert the grade for Student 2"); grade = scan.nextDouble(); st2 = new Student(name,grade);

compareStudents(st1,st2); }}

2015

Page 115: Ifi7184 lesson7

@ Sonia Sousa 115

class Student{ private String name; private double grade; public final double MAXGRADE=20;

// Constructor: Sets the student’s name and initial grade. public Student (String name1, double grade1){ name = name1; grade = grade1; }

// Returns the student's name String getName(){ return name;}

// Returns the student's grade double getGrade(){return grade;} // Increase the studens's grade double increaseGrade(){ if (grade < MAXGRADE);

{grade++;} return grade; } }

2015

Continue

Page 116: Ifi7184 lesson7

@ Sonia Sousa 116

Data Scope• The scope of data is the area in a program in which that

data can be referenced (used)

• Data declared at the class level can be referenced by all methods in that class

• Data declared within a method can be used only in that method

• Data declared within a method is called local data

• In the compareStudents class, the variable scan is declared inside the main method -- it is local to that method and cannot be referenced anywhere else

2015

Page 117: Ifi7184 lesson7

@ Sonia Sousa 117

Instance Data

• A variable declared at the class level (such as name) is called class attribute or instance variable

• Each instance (object) has its own instance variable

• A class declares the type of the data, but it does not reserve memory space for it

• Each time a Student object is created, a new name variable is created as well

• The objects of a class share the method definitions, but each object has its own data space

• That's the only way two objects can have different states

2015

Page 118: Ifi7184 lesson7

@ Sonia Sousa 118

See

• RollingDice.java • Die.java

2015

Page 119: Ifi7184 lesson7

119@ Sonia Sousa

//********************************************************************// RollingDice.java Author: Lewis/Loftus//// Demonstrates the creation and use of a user-defined class.//********************************************************************

public class RollingDice{ //----------------------------------------------------------------- // Creates two Die objects and rolls them several times. //----------------------------------------------------------------- public static void main (String[] args) { Die die1, die2; int sum;

die1 = new Die(); die2 = new Die();

die1.roll(); die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2);

continue

2015

Page 120: Ifi7184 lesson7

@ Sonia Sousa 120

continue

die1.roll(); die2.setFaceValue(4); System.out.println ("Die One: " + die1 + ", Die Two: " + die2);

sum = die1.getFaceValue() + die2.getFaceValue(); System.out.println ("Sum: " + sum);

sum = die1.roll() + die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); System.out.println ("New sum: " + sum); }}

2015

Page 121: Ifi7184 lesson7

@ Sonia Sousa 121

continue

die1.roll(); die2.setFaceValue(4); System.out.println ("Die One: " + die1 + ", Die Two: " + die2);

sum = die1.getFaceValue() + die2.getFaceValue(); System.out.println ("Sum: " + sum);

sum = die1.roll() + die2.roll(); System.out.println ("Die One: " + die1 + ", Die Two: " + die2); System.out.println ("New sum: " + sum); }}

Sample RunDie One: 5, Die Two: 2Die One: 1, Die Two: 4Sum: 5Die One: 4, Die Two: 2New sum: 6

2015

Page 122: Ifi7184 lesson7

@ Sonia Sousa 122

//********************************************************************// Die.java Author: Lewis/Loftus//// Represents one die (singular of dice) with faces showing values// between 1 and 6.//********************************************************************

public class Die{ private final int MAX = 6; // maximum face value

private int faceValue; // current value showing on the die

//----------------------------------------------------------------- // Constructor: Sets the initial face value. //----------------------------------------------------------------- public Die() { faceValue = 1; }

continue

2015

Page 123: Ifi7184 lesson7

@ Sonia Sousa 123

continue

//----------------------------------------------------------------- // Rolls the die and returns the result. //----------------------------------------------------------------- public int roll() { faceValue = (int)(Math.random() * MAX) + 1; return faceValue; }

//----------------------------------------------------------------- // Face value mutator. //----------------------------------------------------------------- public void setFaceValue (int value) { faceValue = value; }

//----------------------------------------------------------------- // Face value accessor. //----------------------------------------------------------------- public int getFaceValue() { return faceValue; }

continue

2015

Page 124: Ifi7184 lesson7

@ Sonia Sousa 124

continue

//----------------------------------------------------------------- // Returns a string representation of this die. //----------------------------------------------------------------- public String toString() { String result = Integer.toString(faceValue);

return result; }}

2015

Page 125: Ifi7184 lesson7

@ Sonia Sousa 125

The toString Method

• It's good practice to define a toString method for a class

• The toString method returns a character string that represents the object in some way

• It is called automatically when an object is concatenated to a string or when it is passed to the println method

• It's also convenient for debugging problems

2015

Page 126: Ifi7184 lesson7

@ Sonia Sousa 126

Data Scope• The scope of data is the area in a program in which

that data can be referenced (used)

• Data declared at the class level can be referenced by all methods in that class

• Data declared within a method can be used only in that method

• Data declared within a method is called local data• In the Die class, the variable result is declared

inside the toString method -- it is local to that method and cannot be referenced anywhere else

2015

Page 127: Ifi7184 lesson7

@ Sonia Sousa 127

Instance Data

• A variable declared at the class level (such as faceValue) is called instance data

• Each instance (object) has its own instance variable

• A class declares the type of the data, but it does not reserve memory space for it

• Each time a Die object is created, a new faceValue variable is created as well

• The objects of a class share the method definitions, but each object has its own data space

• That's the only way two objects can have different states

2015

Page 128: Ifi7184 lesson7

@ Sonia Sousa 128

UML Diagrams

• UML stands for the Unified Modeling Language• UML diagrams show relationships among classes

and objects

• A UML class diagram consists of one or more classes, each with sections for the class name, attributes (data), and operations (methods)

• Lines between classes represent associations• A dotted arrow shows that one class uses the other

(calls its methods)

2015

Page 129: Ifi7184 lesson7

UML Class Diagrams• A UML class diagram for the RollingDice

program:

RollingDice

main (args : String[]) : void

DiefaceValue : int

roll() : int

1292015 @ Sonia Sousa 3-129