This document discusses program development and outlines a lesson on object-oriented programming concepts. It covers the four basic activities of program development: establishing requirements, creating a design, implementing code, and testing. It then outlines topics to be covered in the lesson including method design, creating objects, loop statements, classes and objects, and more. Examples are provided of creating classes to represent dice and students. The use of for loops is demonstrated through examples printing weekdays, multiples of a number, and a triangle of asterisks.
2. Lesson 7 - Outline
22015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
extra
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 @ Sonia Sousa 3
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 @ Sonia Sousa 4
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 @ Sonia Sousa 5
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 @ Sonia Sousa 6
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 @ Sonia Sousa 7
8. Lesson 7 - Outline
82015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
extra
9. Anatomy of a Class
Creating Students objects
2015 @ Sonia Sousa 9
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
10@ Sonia Sousa2015
11. Creating Objects
• An object has:
– state (attributes)
– String name
– double grade
• descriptive characteristics
– behaviors (what he can
do)
– compareStudents
11
StudentCompare
Name
Grade
compareStudents
Student
@ Sonia Sousa2015
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
12@ Sonia Sousa2015
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
13@ Sonia Sousa2015
14. // 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 14
2015 @ 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);
} 15@ Sonia Sousa
continue
2015
16. Instance Data
• We can depict the two Student objects
from the Student program as follows:
16
st1 Johnname
st2 Maryname
Each object maintains its own name variable, and
thus its own state
@ Sonia Sousa2015
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.
17@ Sonia Sousa2015
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
@ Sonia Sousa 182015
19. Anatomy of a Class
Creating Die objects
2015 @ Sonia Sousa 19
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.
20@ Sonia Sousa2015
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;
21@ Sonia Sousa2015
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
@ Sonia Sousa 222015
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 value
private 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
@ Sonia Sousa 232015
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()));
}
}
@ Sonia Sousa 242015
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
@ Sonia Sousa 252015
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.
@ Sonia Sousa 262015
27. Anatomy of a Class
Additional examples
2015 @ Sonia Sousa 27
28. Lesson 7 - Outline
282015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
extra
29. The for Statement
• A for statement has the following syntax:
for ( initialization ; condition ; increment )
statement;
The initialization
is executed once
before the loop begins
The statement is
executed until the
condition becomes false
The increment portion is executed at
the end of each iteration
2015 @ Sonia Sousa 29
30. Logic of a for loop
statement
true
condition
evaluated
false
increment
initialization
2015 @ Sonia Sousa 30
31. The for Statement
• A for loop is functionally equivalent to the
following while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
2015 @ Sonia Sousa 31
32. The for Statement
• The initialization section can be used to
declare a variable
for (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 @ Sonia Sousa 32
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 Sousa2015 33
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 @ Sonia Sousa 35
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 loop
for (int i = 0; i < weekDays.length; i++) {
System.out.println(weekDays[i]);
}
}
}
362015 @ 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 @ Sonia Sousa 38
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 @ Sonia Sousa 39
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 @ Sonia Sousa 40
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 Run
Enter a positive value: 7
Enter an upper limit: 400
The multiples of 7 between 7 and 400 (inclusive) are:
7 14 21 28 35
42 49 56 63 70
77 84 91 98 105
112 119 126 133 140
147 154 161 168 175
182 189 196 203 210
217 224 231 238 245
252 259 266 273 280
287 294 301 308 315
322 329 336 343 350
357 364 371 378 385
392 399
2015 @ Sonia Sousa 41
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 @ Sonia Sousa 43
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 @ Sonia Sousa 44
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 45
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 @ Sonia Sousa 46
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 @ Sonia Sousa 47
48. Lesson 7 - Outline
482015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
extra
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 @ Sonia Sousa 49
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 by
its primary characteristics, including its name and
product number. If the bar code does not match the
product, then an error should be generated to the
message window and entered into the error log. The
summary report of all transactions must be structured
as specified in section 7.A.
2015 @ Sonia Sousa 50
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 @ Sonia Sousa 51
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 @ Sonia Sousa 52
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 @ Sonia Sousa 53
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 @ Sonia Sousa 54
55. Lesson 7 - Outline
552015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Wrapper Classes
Static Variables and Methods
Class Relationships
Extra
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 Season
enum Season {winter, spring, summer, fall};
• Any number of values can be listed
2015 @ Sonia Sousa 56
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 @ Sonia Sousa 57
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 @ Sonia Sousa 58
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 @ Sonia Sousa 59
64. Lesson 7 - Outline
642015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
Extra
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 @ Sonia Sousa 65
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 @ Sonia Sousa 66
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 @ Sonia Sousa 67
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 @ Sonia Sousa 68
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 @ Sonia Sousa 69
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 @ Sonia Sousa 70
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 @ Sonia Sousa 71
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 @ Sonia Sousa 72
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());
}
}
Output
Remember the Alamo.
Don't Worry. Be Happy.
Live Free or Die.
Talk is Cheap.
Write Once, Run Anywhere.
Slogans created: 5
2015 @ Sonia Sousa 73
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 74
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 @ Sonia Sousa 75
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 @ Sonia Sousa 76
77. Lesson 7 - Outline
772015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
Extra
78. Wrapper Classes
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
• The java.lang package contains wrapper
classes that correspond to each primitive type:
2015 @ Sonia Sousa 78
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
792015 @ 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
802015 @ 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
812015 @ Sonia Sousa
82. Quick Check
• Are the following assignments valid? Explain.
Double value = 15.75;
Character ch = new Character('T');
char myChar = ch;
822015 @ 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;
832015 @ Sonia Sousa
84. Lesson 7 - Outline
842015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
Extra
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 @ Sonia Sousa 85
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 @ Sonia Sousa 86
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 @ Sonia Sousa 87
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 @ Sonia Sousa 88
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 @ Sonia Sousa 89
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 @ Sonia Sousa 90
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);
}
}
Output
First rational number: 3/4
Second rational number: 1/3
r1 and r2 are NOT equal.
The reciprocal of r1 is: 4/3
r1 + r2: 13/12
r1 - r2: 5/12
r1 * r2: 1/4
r1 / r2: 9/4
2015 @ Sonia Sousa 91
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 @ Sonia Sousa 92
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 @ Sonia Sousa 93
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 @ Sonia Sousa 94
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);
}
continue
2015 @ Sonia Sousa 95
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 @ Sonia Sousa 96
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 @ Sonia Sousa 97
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 @ Sonia Sousa 98
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 @ Sonia Sousa 99
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 @ Sonia Sousa 100
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 @ Sonia Sousa 101
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 @ Sonia Sousa 102
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);
}
}
Output
John Smith
Home Address:
21 Jump Street
Lynchburg, VA 24551
School Address:
800 Lancaster Ave.
Villanova, PA 19085
Marsha Jones
Home Address:
123 Main Street
Euclid, OH 44132
School Address:
800 Lancaster Ave.
Villanova, PA 19085
2015 @ Sonia Sousa 103
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 @ Sonia Sousa 104
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 @ Sonia Sousa 105
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 @ Sonia Sousa 106
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 @ Sonia Sousa 109
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 @ Sonia Sousa 110
111. Lesson 7 - Outline
1112015 @ Sonia Sousa
Method Design
Creating Objects
Loop statements
Identifying Classes and Objects
Enumerated Types
Static Variables and Methods
Wrapper Classes
Class Relationships
extra
112. Anatomy of a Class
Additional examples
2015 @ Sonia Sousa 112
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");}
}
}
113@ Sonia Sousa2015
continue
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);
}
}
114@ Sonia Sousa2015
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;
}
}
115@ Sonia Sousa2015
Continue
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
116@ Sonia Sousa2015
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
117@ Sonia Sousa2015
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
1192015
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 Run
Die One: 5, Die Two: 2
Die One: 1, Die Two: 4
Sum: 5
Die One: 4, Die Two: 2
New sum: 6
@ Sonia Sousa 1212015
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
@ Sonia Sousa 1222015
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
@ Sonia Sousa 1232015
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
@ Sonia Sousa 1252015
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
@ Sonia Sousa 1262015
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
@ Sonia Sousa 1272015
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)
@ Sonia Sousa 1282015
129. UML Class Diagrams
• A UML class diagram for the RollingDice
program:
RollingDice
main (args : String[]) : void
Die
faceValue : int
roll() : int
1292015 @ Sonia Sousa
3-129