SlideShare a Scribd company logo
1 of 129
IFI7184.DT – Lesson 7
2015 @ Sonia Sousa 1
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
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
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
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
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
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
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
Anatomy of a Class
Creating Students objects
2015 @ Sonia Sousa 9
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
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
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
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
// 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
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
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
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
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
Anatomy of a Class
Creating Die objects
2015 @ Sonia Sousa 19
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
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
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
//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
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
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
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
Anatomy of a Class
Additional examples
2015 @ Sonia Sousa 27
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
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
Logic of a for loop
statement
true
condition
evaluated
false
increment
initialization
2015 @ Sonia Sousa 30
The for Statement
• A for loop is functionally equivalent to the
following while loop structure:
initialization;
while ( condition )
{
statement;
increment;
}
2015 @ Sonia Sousa 31
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
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
The For Statement
Demonstrating a for loop using an array
of Strings
2015 @ Sonia Sousa 34
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
// 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
The For Statement
Demonstrates the use of a for loop to
print a sequence of numbers.
2015 @ Sonia Sousa 37
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
//********************************************************************
// 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
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
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
The For Statement
Demonstrates the use of nested for
loops.
2015 @ Sonia Sousa 42
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
//********************************************************************
// 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
@ 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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
Enumerated Types
Demonstrates the use of enumerated
types
2015 @ Sonia Sousa 60
//********************************************************************
// 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 @ Sonia Sousa 61
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 @ 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());
}
}
Output
cone1 value: rockyRoad
cone1 ordinal: 5
cone1 name: rockyRoad
cone2 value: chocolate
cone2 ordinal: 1
cone2 name: chocolate
cone3 value: rockyRoad
cone3 ordinal: 5
cone3 name: rockyRoad
2015 @ Sonia Sousa 63
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
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
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
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
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
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
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
//********************************************************************
// 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
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
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
@ 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
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
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
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
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
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
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
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
Quick Check
• Are the following assignments valid? Explain.
Double value = 15.75;
Character ch = new Character('T');
char myChar = ch;
822015 @ Sonia Sousa
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
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
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
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
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
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
//********************************************************************
// 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
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
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
//********************************************************************
// 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
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
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
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
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
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
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
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
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
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
//********************************************************************
// 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
//********************************************************************
// 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
//********************************************************************
// 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
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
//********************************************************************
// 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
continue
//-----------------------------------------------------------------
// Returns a description of this Address object.
//-----------------------------------------------------------------
public String toString()
{
String result;
result = streetAddress + "n";
result += city + ", " + state + " " + zipCode;
return result;
}
}
2015 @ Sonia Sousa 107
Aggregation in UML
StudentBody
+ 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 @ Sonia Sousa 108
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
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
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
Anatomy of a Class
Additional examples
2015 @ Sonia Sousa 112
// 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
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
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
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
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
See
• RollingDice.java
• Die.java
@ Sonia Sousa 1182015
@ 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
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);
}
}
@ Sonia Sousa 1202015
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
//********************************************************************
// 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
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
continue
//-----------------------------------------------------------------
// Returns a string representation of this die.
//-----------------------------------------------------------------
public String toString()
{
String result = Integer.toString(faceValue);
return result;
}
}
@ Sonia Sousa 1242015
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
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
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
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
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

More Related Content

What's hot

[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 
Software Engineering :UML class diagrams
Software Engineering :UML class diagramsSoftware Engineering :UML class diagrams
Software Engineering :UML class diagramsAjit Nayak
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsHarsh Patel
 
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Third...
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Third...Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Third...
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Third...Wagdy Mohamed
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan collegeahmed hmed
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for HaskellMartin Ockajak
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOPMuhammad Hammad Waseem
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java DevelopersMartin Ockajak
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & ScalaMartin Ockajak
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and MethodsNilesh Dalvi
 
Machine Learning - Dummy Variable Conversion
Machine Learning - Dummy Variable ConversionMachine Learning - Dummy Variable Conversion
Machine Learning - Dummy Variable ConversionAndrew Ferlitsch
 
.NET F# Abstract class interface
.NET F# Abstract class interface.NET F# Abstract class interface
.NET F# Abstract class interfaceDrRajeshreeKhande
 

What's hot (19)

[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
Software Engineering :UML class diagrams
Software Engineering :UML class diagramsSoftware Engineering :UML class diagrams
Software Engineering :UML class diagrams
 
Chap01
Chap01Chap01
Chap01
 
Java Basics
Java BasicsJava Basics
Java Basics
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Third...
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Third...Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Third...
Microsoft Tech Club Cairo University "MSTC'16 Builders and Developers " Third...
 
[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member[OOP - Lec 18] Static Data Member
[OOP - Lec 18] Static Data Member
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan college
 
Sep 15
Sep 15Sep 15
Sep 15
 
Sep 15
Sep 15Sep 15
Sep 15
 
Refinement Types for Haskell
Refinement Types for HaskellRefinement Types for Haskell
Refinement Types for Haskell
 
[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP[OOP - Lec 04,05] Basic Building Blocks of OOP
[OOP - Lec 04,05] Basic Building Blocks of OOP
 
[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects[OOP - Lec 06] Classes and Objects
[OOP - Lec 06] Classes and Objects
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
Comparing Haskell & Scala
Comparing Haskell & ScalaComparing Haskell & Scala
Comparing Haskell & Scala
 
Final keyword in java
Final keyword in javaFinal keyword in java
Final keyword in java
 
4. Classes and Methods
4. Classes and Methods4. Classes and Methods
4. Classes and Methods
 
Machine Learning - Dummy Variable Conversion
Machine Learning - Dummy Variable ConversionMachine Learning - Dummy Variable Conversion
Machine Learning - Dummy Variable Conversion
 
.NET F# Abstract class interface
.NET F# Abstract class interface.NET F# Abstract class interface
.NET F# Abstract class interface
 

Viewers also liked

A key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactionsA key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactionsSónia
 
Trust workshop
Trust workshopTrust workshop
Trust workshopSónia
 
Ifi7174 lesson1
Ifi7174 lesson1Ifi7174 lesson1
Ifi7174 lesson1Sónia
 
Ifi7174 lesson4
Ifi7174 lesson4Ifi7174 lesson4
Ifi7174 lesson4Sónia
 
Literature, Law and Learning: Excursions from Computer Science
Literature, Law and Learning: Excursions from Computer ScienceLiterature, Law and Learning: Excursions from Computer Science
Literature, Law and Learning: Excursions from Computer ScienceClare Hooper
 
Ifi7174 lesson2
Ifi7174 lesson2Ifi7174 lesson2
Ifi7174 lesson2Sónia
 
Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective Sónia
 
Helping users in assessing the trustworthiness of user-generated reviews
Helping users in assessing the trustworthiness of user-generated reviewsHelping users in assessing the trustworthiness of user-generated reviews
Helping users in assessing the trustworthiness of user-generated reviewsThe Research Thing
 
Technology, Trust, & Transparency
Technology, Trust, & TransparencyTechnology, Trust, & Transparency
Technology, Trust, & TransparencyGeek Girls
 
Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2Sónia
 
Technology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point FinalTechnology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point Finaljhustad1
 
Workshop 1
Workshop 1Workshop 1
Workshop 1Sónia
 
A design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction DesignA design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction DesignSónia
 
MG673 - Session 1
MG673 - Session 1MG673 - Session 1
MG673 - Session 1Sónia
 
Technology and Trust: The Challenge of 21st Century Government
Technology and Trust: The Challenge of 21st Century GovernmentTechnology and Trust: The Challenge of 21st Century Government
Technology and Trust: The Challenge of 21st Century GovernmentTim O'Reilly
 
Trust in IT: Factors, Metrics and Models
Trust in IT: Factors, Metrics and ModelsTrust in IT: Factors, Metrics and Models
Trust in IT: Factors, Metrics and ModelsClare Hooper
 
An Operating System for the Real World
An Operating System for the Real WorldAn Operating System for the Real World
An Operating System for the Real WorldTim O'Reilly
 

Viewers also liked (20)

A key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactionsA key contribution for leveraging trustful interactions
A key contribution for leveraging trustful interactions
 
Trust workshop
Trust workshopTrust workshop
Trust workshop
 
Lesson 17
Lesson 17Lesson 17
Lesson 17
 
Nettets genkomst?
Nettets genkomst?Nettets genkomst?
Nettets genkomst?
 
Ifi7174 lesson1
Ifi7174 lesson1Ifi7174 lesson1
Ifi7174 lesson1
 
My ph.d Defence
My ph.d DefenceMy ph.d Defence
My ph.d Defence
 
Ifi7174 lesson4
Ifi7174 lesson4Ifi7174 lesson4
Ifi7174 lesson4
 
Literature, Law and Learning: Excursions from Computer Science
Literature, Law and Learning: Excursions from Computer ScienceLiterature, Law and Learning: Excursions from Computer Science
Literature, Law and Learning: Excursions from Computer Science
 
Ifi7174 lesson2
Ifi7174 lesson2Ifi7174 lesson2
Ifi7174 lesson2
 
Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective Trust from a Human Computer Interaction perspective
Trust from a Human Computer Interaction perspective
 
Helping users in assessing the trustworthiness of user-generated reviews
Helping users in assessing the trustworthiness of user-generated reviewsHelping users in assessing the trustworthiness of user-generated reviews
Helping users in assessing the trustworthiness of user-generated reviews
 
Technology, Trust, & Transparency
Technology, Trust, & TransparencyTechnology, Trust, & Transparency
Technology, Trust, & Transparency
 
Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2Developing Interactive systems - lesson 2
Developing Interactive systems - lesson 2
 
Technology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point FinalTechnology Trust 08 24 09 Power Point Final
Technology Trust 08 24 09 Power Point Final
 
Workshop 1
Workshop 1Workshop 1
Workshop 1
 
A design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction DesignA design space for Trust-enabling Interaction Design
A design space for Trust-enabling Interaction Design
 
MG673 - Session 1
MG673 - Session 1MG673 - Session 1
MG673 - Session 1
 
Technology and Trust: The Challenge of 21st Century Government
Technology and Trust: The Challenge of 21st Century GovernmentTechnology and Trust: The Challenge of 21st Century Government
Technology and Trust: The Challenge of 21st Century Government
 
Trust in IT: Factors, Metrics and Models
Trust in IT: Factors, Metrics and ModelsTrust in IT: Factors, Metrics and Models
Trust in IT: Factors, Metrics and Models
 
An Operating System for the Real World
An Operating System for the Real WorldAn Operating System for the Real World
An Operating System for the Real World
 

Similar to Ifi7184 lesson7

IFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languagesIFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languagesSónia
 
lecture-18staticdatamember-160705095116.pdf
lecture-18staticdatamember-160705095116.pdflecture-18staticdatamember-160705095116.pdf
lecture-18staticdatamember-160705095116.pdfAneesAbbasi14
 
static members in object oriented program.pptx
static members in object oriented program.pptxstatic members in object oriented program.pptx
static members in object oriented program.pptxurvashipundir04
 
7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptx7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptxAbhishekkumarsingh630054
 
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesIntroduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesDigitalDsms
 
Classes-and-Object.pptx
Classes-and-Object.pptxClasses-and-Object.pptx
Classes-and-Object.pptxVishwanathanS5
 
Object Oriented Programming Constructors & Destructors
Object Oriented Programming  Constructors &  DestructorsObject Oriented Programming  Constructors &  Destructors
Object Oriented Programming Constructors & Destructorsanitashinde33
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programmingshinyduela
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptxakila m
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptxEpsiba1
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objectsmcollison
 
YASQLT – Yet Another SQL Tutor. A Pragmatic Approach
YASQLT – Yet Another SQL Tutor. A Pragmatic ApproachYASQLT – Yet Another SQL Tutor. A Pragmatic Approach
YASQLT – Yet Another SQL Tutor. A Pragmatic ApproachIlia Bider
 
Section1 compound data class
Section1 compound data classSection1 compound data class
Section1 compound data classDương Tùng
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Getachew Ganfur
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming CourseDennis Chang
 

Similar to Ifi7184 lesson7 (20)

IFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languagesIFI7184.DT lesson1- Programming languages
IFI7184.DT lesson1- Programming languages
 
lecture-18staticdatamember-160705095116.pdf
lecture-18staticdatamember-160705095116.pdflecture-18staticdatamember-160705095116.pdf
lecture-18staticdatamember-160705095116.pdf
 
static members in object oriented program.pptx
static members in object oriented program.pptxstatic members in object oriented program.pptx
static members in object oriented program.pptx
 
Lecture 4
Lecture 4Lecture 4
Lecture 4
 
07slide.ppt
07slide.ppt07slide.ppt
07slide.ppt
 
7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptx7. Pointers and Virtual functions final -3.pptx
7. Pointers and Virtual functions final -3.pptx
 
Introduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book NotesIntroduction to C++ Class & Objects. Book Notes
Introduction to C++ Class & Objects. Book Notes
 
Classes-and-Object.pptx
Classes-and-Object.pptxClasses-and-Object.pptx
Classes-and-Object.pptx
 
Object Oriented Programming Constructors & Destructors
Object Oriented Programming  Constructors &  DestructorsObject Oriented Programming  Constructors &  Destructors
Object Oriented Programming Constructors & Destructors
 
Introduction to java programming
Introduction to java programmingIntroduction to java programming
Introduction to java programming
 
UNIT - IIInew.pptx
UNIT - IIInew.pptxUNIT - IIInew.pptx
UNIT - IIInew.pptx
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Oops in java
Oops in javaOops in java
Oops in java
 
Pi j2.3 objects
Pi j2.3 objectsPi j2.3 objects
Pi j2.3 objects
 
00-review.ppt
00-review.ppt00-review.ppt
00-review.ppt
 
YASQLT – Yet Another SQL Tutor. A Pragmatic Approach
YASQLT – Yet Another SQL Tutor. A Pragmatic ApproachYASQLT – Yet Another SQL Tutor. A Pragmatic Approach
YASQLT – Yet Another SQL Tutor. A Pragmatic Approach
 
Section1 compound data class
Section1 compound data classSection1 compound data class
Section1 compound data class
 
Oop scala
Oop scalaOop scala
Oop scala
 
Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02Ccourse 140618093931-phpapp02
Ccourse 140618093931-phpapp02
 
C++ Programming Course
C++ Programming CourseC++ Programming Course
C++ Programming Course
 

More from Sónia

MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)Sónia
 
Ifi7184.DT lesson 2
Ifi7184.DT lesson 2Ifi7184.DT lesson 2
Ifi7184.DT lesson 2Sónia
 
IFI7184.DT about the course
IFI7184.DT about the courseIFI7184.DT about the course
IFI7184.DT about the courseSónia
 
Comparative evaluation
Comparative evaluationComparative evaluation
Comparative evaluationSónia
 
Ifi7155 Contextualization
Ifi7155 ContextualizationIfi7155 Contextualization
Ifi7155 ContextualizationSónia
 
Hcc lesson7
Hcc lesson7Hcc lesson7
Hcc lesson7Sónia
 
Hcc lesson6
Hcc lesson6Hcc lesson6
Hcc lesson6Sónia
 
eduHcc lesson2-3
eduHcc lesson2-3eduHcc lesson2-3
eduHcc lesson2-3Sónia
 
Human Centered Computing (introduction)
Human Centered Computing (introduction)Human Centered Computing (introduction)
Human Centered Computing (introduction)Sónia
 
20 06-2014
20 06-201420 06-2014
20 06-2014Sónia
 
Ifi7155 project-final
Ifi7155 project-finalIfi7155 project-final
Ifi7155 project-finalSónia
 
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...Sónia
 
Workshop 1 (analysis and Presenting)
Workshop 1 (analysis and Presenting)Workshop 1 (analysis and Presenting)
Workshop 1 (analysis and Presenting)Sónia
 
Workshop 1 - User eXperience evaluation
Workshop 1 - User eXperience evaluationWorkshop 1 - User eXperience evaluation
Workshop 1 - User eXperience evaluationSónia
 

More from Sónia (14)

MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)MGA 673 – Evaluating User Experience (part1)
MGA 673 – Evaluating User Experience (part1)
 
Ifi7184.DT lesson 2
Ifi7184.DT lesson 2Ifi7184.DT lesson 2
Ifi7184.DT lesson 2
 
IFI7184.DT about the course
IFI7184.DT about the courseIFI7184.DT about the course
IFI7184.DT about the course
 
Comparative evaluation
Comparative evaluationComparative evaluation
Comparative evaluation
 
Ifi7155 Contextualization
Ifi7155 ContextualizationIfi7155 Contextualization
Ifi7155 Contextualization
 
Hcc lesson7
Hcc lesson7Hcc lesson7
Hcc lesson7
 
Hcc lesson6
Hcc lesson6Hcc lesson6
Hcc lesson6
 
eduHcc lesson2-3
eduHcc lesson2-3eduHcc lesson2-3
eduHcc lesson2-3
 
Human Centered Computing (introduction)
Human Centered Computing (introduction)Human Centered Computing (introduction)
Human Centered Computing (introduction)
 
20 06-2014
20 06-201420 06-2014
20 06-2014
 
Ifi7155 project-final
Ifi7155 project-finalIfi7155 project-final
Ifi7155 project-final
 
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
Sousa, Sonia; Lamas, David; Dias, Paulo (2012). The Implications of Trust on ...
 
Workshop 1 (analysis and Presenting)
Workshop 1 (analysis and Presenting)Workshop 1 (analysis and Presenting)
Workshop 1 (analysis and Presenting)
 
Workshop 1 - User eXperience evaluation
Workshop 1 - User eXperience evaluationWorkshop 1 - User eXperience evaluation
Workshop 1 - User eXperience evaluation
 

Recently uploaded

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 

Recently uploaded (20)

Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 

Ifi7184 lesson7

  • 1. IFI7184.DT – Lesson 7 2015 @ Sonia Sousa 1
  • 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
  • 34. The For Statement Demonstrating a for loop using an array of Strings 2015 @ Sonia Sousa 34
  • 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
  • 37. The For Statement Demonstrates the use of a for loop to print a sequence of numbers. 2015 @ Sonia Sousa 37
  • 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
  • 42. The For Statement Demonstrates the use of nested for loops. 2015 @ Sonia Sousa 42
  • 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
  • 60. Enumerated Types Demonstrates the use of enumerated types 2015 @ Sonia Sousa 60
  • 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 @ Sonia Sousa 61
  • 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 @ Sonia Sousa 62
  • 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()); } } Output cone1 value: rockyRoad cone1 ordinal: 5 cone1 name: rockyRoad cone2 value: chocolate cone2 ordinal: 1 cone2 name: chocolate cone3 value: rockyRoad cone3 ordinal: 5 cone3 name: rockyRoad 2015 @ Sonia Sousa 63
  • 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
  • 107. continue //----------------------------------------------------------------- // Returns a description of this Address object. //----------------------------------------------------------------- public String toString() { String result; result = streetAddress + "n"; result += city + ", " + state + " " + zipCode; return result; } } 2015 @ Sonia Sousa 107
  • 108. Aggregation in UML StudentBody + 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 @ Sonia Sousa 108
  • 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
  • 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); } } @ Sonia Sousa 1202015
  • 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
  • 124. continue //----------------------------------------------------------------- // Returns a string representation of this die. //----------------------------------------------------------------- public String toString() { String result = Integer.toString(faceValue); return result; } } @ Sonia Sousa 1242015
  • 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