Sunteți pe pagina 1din 51

presentation slides for

Object-Oriented Problem Solving


JAVA, JAVA, JAVA
Second Edition

Ralph Morelli
Trinity College
Hartford, CT

published by Prentice
Hall
Java, Java, Java
Object Oriented Problem Solving

Chapter 2 Objects:
Defining, Creating, and Using
Objectives
• Be familiar with the relationship between
classes and objects in a Java program.
• Be able to understand and write simple
programs in Java.
• Be familiar with some of the basic
principles of object-oriented programming.
• Understand some of the basic elements of
the Java language.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Outline

• Class Definition
• Case Study: Simulating a CyberPet
• Object-Oriented Design: Basic
Principles
• Java Language Summary
• From the Java Library: BufferedReader,
String, Integer
• In the Laboratory: The Circle Class
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Class Definition
• Five basic design questions:
– What role will the object perform?
– What data or information will it need?
– What actions will it take?
– What public interface will it present to
other objects?
– What information will it hide (keep
private) from other objects?

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
The Rectangle Class
• A class is a blueprint. It describes an object's form
but it has no content.

The instance variables, length


and width, have no values yet.

The class contains an


object’s method definitions

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
The Rectangle Class Definition
public class Rectangle
{
private double length; // Instance variables
A public class is accessible
private double width; to other classes
public Rectangle(double l, double w) // Constructor method
{
length = l;
width = w; Instance variables
} // Rectangle constructor
are usually private
public double calculateArea() // Access method
{
return length * width;
} // calculateArea

} // Rectangle class
An object’s public methods
make up its interface

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
The RectangleUser Class
• The RectangleUser class will create and
use 1 or more Rectangle instances.

An application has a
main() method

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
The RectangleUser Class Definition
Class
Definition
An application must
public class RectangleUser have a main() method
{
public static void main(String argv[])
{
Object
Rectangle rectangle1 = new Rectangle(30,10); Creation
Rectangle rectangle2 = new Rectangle(25,20);
System.out.println("rectangle1 area " +
rectangle1.calculateArea());
System.out.println("rectangle2 area " +
rectangle2.calculateArea());
} // main()
} // RectangleUser
Object
Use

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Creating Rectangle Instances
• Create, or instantiate, two instances of the Rectangle
class:
Rectangle rectangle1 = new Rectangle(30,10);
Rectangle rectangle2 = new Rectangle(25, 20);

The objects (instances)


store actual values.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Using Rectangle Instances
• We use a method call to ask each object to
tell us its area:
System.out.println("rectangle1 area " + rectangle1.calculateArea());
System.out.println("rectangle2 area " + rectangle2.calculateArea());

References to Method calls


objects

rectangle1 area 300


Printed output: rectangle2 area 500

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Define, Create, Use

• Class definition: Define one or more classes


(Rectangle, RectangleUser)
• Object Instantiation: Create objects as
instances of the classes (rectangle1,
rectangle2)
• Object Use: Use the objects to do tasks
(rectangle1.calculateArea() )

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Case Study: Simulating a CyberPet

• Design Steps
– Problem Specification
– Problem Decomposition
– Class Design: CyberPet
– Method Decomposition
– CyberPet Design Specification

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Problem Specification
• Design a program that allows the user to
interact with objects that simulate the
behavior of a CyberPet.

• A CyberPet will perform two behaviors,


eating and sleeping, when we tell it to.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Problem Decomposition

• What objects do we need?

TestCyberPet serves as a
user interface. It creates and
uses CyberPets

CyberPet objects encapsulate


CyberPet state and behavior.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Class Design: CyberPet
• State: boolean variables, isEating and isSleeping

• Methods:
– A constructor to initialize a CyberPet
– An eat method to put pet in eating state
– A sleep method to put pet in sleeping state

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
CyberPet Class Specification
• Class Name: CyberPet
– Role: To represent and simulate a CyberPet
• Information Needed (instance variables)
– isEating: Set to true when pet is eating (private)
– isSleeping: Set to true when pet is sleeping (private)
• Manipulations Needed (public methods)
– CyberPet(): A constructor method to initialize the pet
– sleep(): A method to put the pet in sleeping state
– eat(): A method to get the pet in eating state

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
CyberPet Class Definition
public class CyberPet
{
// Data
private boolean isEating = true;// CyberPet's state
private boolean isSleeping = false;
// Methods
public void eat() // Start eating
{
isEating = true; // Change the state
isSleeping = false;
System.out.println("Pet is eating");
return;
} // eat()
public void sleep() // Start sleeping
{ If no constructor
isSleeping = true; // Change the state
isEating = false; method, Java
System.out.println("Pet is sleeping");
return; provides a default.
} // sleep()
} // CyberPet class

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
The CyberPet Class
• A class is a blueprint. In this case every
CyberPet created will be in the eating state
initially.

The instance variables,


isEating and isSleeping, have
initial values.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
The Class Header

• Example:

public class CyberPet

• In General:
ClassModifiersopt class ClassName Pedigreeopt

public class CyberPet extends Object

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Identifiers
• An identifier is a name for a variable,
method, or class.
• Rule: An identifier in Java must begin with
a letter, and may consist of any number of
letters, digits, and underscore (_) characters.
• Legal: CyberPet, eat, sleep, pet1, pet_2
• Illegal: Cyber Pet, 30days, pet$, n!

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Declaring Instance Variables

• Examples:
// Instance variables
private boolean isEating = true;
private boolean isSleeping = false;

• In General
FieldModifiersopt TypeId VariableId Initializeropt

• Fields or instance variables have class scope.


Their names can be used anywhere within the
class.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Public/Private Access
• Instance variables should usually be
declared private. This makes them
inaccessible to other objects.
• Generally, public methods are used to
provide carefully controlled access to the
private variables.
• An object’s public methods make up its
interface -- that part of its makeup that is
accessible to other objects.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Public/Private Access (cont)

• Possible Error: Public instance variables can


lead to an inconsistent state
• Example: Suppose we make isEating and
isSleeping public variables.
george.isEating = true; // Inconsistent
george.isSleeping = true; // State

• The proper way to make george eat:


george.eat(); // eat() is public method

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Initializer Expressions
• General Form: Variable = expression
• The expression on the right of the assignment
operator (=) is evaluated and its value is
stored in the variable on the left.
• Examples:
private boolean isEating = true;
private int petSize = 10;
private int petAge = true; // Type error

• Type error: You can’t assign a boolean


value to an int variable
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Method Definition
• Example
public void MethodName() // Method Header
{ // Start of method body
} // End of method body

• The Method Header


MethodModifiersopt ResultType MethodName (ParameterList )

public static void main (String argv[] )


public void paint (Graphics g)
public void init ()
public void eat ()

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Method Definition

Header: This method, named


eat, is accessible to other
public void eat() objects (public), and does not
{ return a value (void).
isEating = true;
isSleeping = false;
System.out.println("Pet is eating");
return;
} // eat()

Body: a block of statements


that sets the CyberPet’s state
to eating.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Designing Methods
• The public methods serve as a class’s
interface.
• If a method is intended to be used to
communicate with or pass information to an
object, it should be declared public.
• A class’s methods have class scope. They
can be used anywhere within the class.
• Methods that do not return a value should
be declared void.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
The Simple Assignment Statement
• General Form: VariableName = Expression
• The expression on the right of the assignment
operator (=) is evaluated and its value is stored
in the variable on the left.
• Examples:
isEating = true;
isSleeping = false;
isEating = 100; // Type error

• Type error: The value being assigned must


be the same type as the variable.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Creating CyberPet Instances
• A reference variable refers to an object by storing the address of the object.

// Declare a reference variable


CyberPet pet1;

(a) The reference variable, pet1,


will refer to a CyberPet (b) , but
its initial value is null.

// Create an instance
pet1 = new CyberPet();

(c) After instantiation, pet1


refers to a CyberPet

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Creating CyberPet Instances (cont)
• Declare and instantiate in one statement:
CyberPet pet1 = new CyberPet();
CyberPet pet2 = new CyberPet();

Two CyberPets with names, pet1


and pet2, both eating.

UML Object Diagram


Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Using and Manipulating CyberPets
• Objects are used by calling one of their public
methods:
pet1.eat(); // Tell pet1 to eat
pet2.sleep(); // Tell pet2 to sleep

Now pet1 is
eating but pet2 is
sleeping.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
The TestCyberPet Class
public class TestCyberPet
{
public static void main (String argv[])
{
// Execution starts here
System.out.println("main() is starting");
CyberPet pet1; // Declare two references
CyberPet pet2;
pet1 = new CyberPet(); // Instantiate the references
pet2 = new CyberPet(); // by creating new objects
pet1.sleep(); // Tell pet1 to sleep.
pet1.eat(); // Tell pet1 to eat.
pet2.sleep(); // Tell pet2 to sleep.
System.out.println("main() is finished");
return; // Return to the system
} // main()
} //TestCyberPet

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
An Applet Interface
• The TestCyberPetApplet will serve as a user interface
for the CyberPet simulation.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
The TestCyberPetApplet Class
public class TestCyberPetApplet extends Applet
{
public void init()
{
// Execution starts here
System.out.println("init() is starting");
CyberPet pet1; // Declare two references
CyberPet pet2;
pet1 = new CyberPet(); // Instantiate the references
pet2 = new CyberPet(); // by creating new objects
pet1.sleep(); // Tell pet1 to sleep.
pet1.eat(); // Tell pet1 to eat.
pet2.sleep(); // Tell pet2 to sleep.
System.out.println("init() is finished");
return; // Return to the system
} // main()
} //TestCyberPetApplet

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
CyberPet Application
• The CyberPet class can be turned into an application
by giving it a main() method.

Same main() as in
TestCyberPet class

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Method Call and Return
• A method call causes a program to transfer control to the first statement in the called method.
• A return statement returns control to the calling statement.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Tracing TestCyberPet
public static void main (String argv[]) public class CyberPet {
{ 5,8 private boolean isEating = true;
1 System.out.println("main() is starting"); 6,9 private boolean isSleeping = false;
2 CyberPet pet1;
public void eat() {
3 CyberPet pet2;
16 isEating = true;
4 pet1 = new CyberPet(); 17 isSleeping = false;
7 pet2 = new CyberPet(); 18 System.out.println("Pet is eating");
10 pet1.sleep(); 19 return;
15 pet1.eat(); } // eat()
20 pet2.sleep();
public void sleep() {
25 System.out.println("main() is finished"); 11,21 isSleeping = true;
26 return; 12,22 isEating = false;
} // main() 13,23 System.out.println("Pet is sleeping");
14,24 return;
} // sleep()
} // CyberPet class

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Object Oriented Design
• Encapsulation: The CyberPet class
encapsulates a state and a set of actions.
• Information Hiding: CyberPet’s state is
private.
• Interface: CyberPet’s public methods, eat()
and sleep(), limit the way it can be used.
• Generality/Extensibility: We can easily
extend CyberPet’s functionality.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
From the Library: BufferedReader
• Code Reuse Principle: Before designing and writing
your own code, search the Java library for a class that
solves your problem.
• The java.io.BufferedReader class contains methods to
perform keyboard I/O.

public class BufferedReader extends Reader


{
public BufferedReader(Reader in);
public String readLine(); // Read one line
}

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Example: Input a String

import java.io.*; // Java I/O classes


Create a reader.
public class Hello // Performs screen I/O
{
public static void main(String argv[])
throws IOException
{
BufferedReader input = new BufferedReader
(new InputStreamReader(System.in));
System.out.print("Hello, input your name please");
String inputString = input.readLine();
System.out.println("Hello " + inputString);

} // main()
} // Hello Read one line.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
From the Library: Integer
• The java.lang.Integer class is a wrapper class
that contains methods to convert primitive
data into objects and vice versa.
• The parseInt() method converts a String into
an int.
• Example: Converts “54” into 54
int number = Integer.parseInt( “54”);

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Example: Input a Number
public class Grader {
public static void main(String argv[]) throws IOException {
BufferedReader input = new BufferedReader
(new InputStreamReader(System.in));
String inputString;

int midterm1, midterm2, finalExam; // Three exam grades


float sum; // The sum of the 3 grades

System.out.print("Input your grade on the first midterm: ");


inputString = input.readLine();
midterm1 = Integer.parseInt(inputString);
System.out.println("You input: " + midterm1); Read an integer.
// Similar code deleted here to input midterm2 and finalExam
sum = midterm1 + midterm2 + finalExam;
System.out.print("Your average in this course is ");
System.out.println(sum/3);
} // main()
} // Grader

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
In the Laboratory: The Circle Class
• Objectives
– To give practice designing a simple Java class to
represent a geometric circle.
– To convert the design into a working Java program.
– To compile, run, and test the Java program.
• Problem Statement: Design and implement a class
to represent a geometric circle, and test your class
by implementing a main() method that creates
Circle instances and displays their circumferences
and areas.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
In the Laboratory (cont)
• Design: Model your design after the
Rectangle class from Chapter 1.
• Develop a detailed specification.
• Use comments to document your code.
• Use stepwise refinement when coding.
• Sample Output:
The diameter of circle1 is 20.0
The area of circle1 is 314.0
The circumference of circle1 is 62.80
The diameter of circle2 is 30.0
The area of circle2 is 706.5
The circumference of circle2 is 94.2

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Summary: Technical Terms

access modifier assignment statement


class scope escape sequence
field declaration floating point number
flow of control keyword
identifier initializer expression
instance integer
interface literal
method call and return qualified name
void method wrapper class

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Summary: Key Points
• A Java program is a set of interacting objects.
• A Java class serves as a template for objects.
• Classes contain instance variables (state) and
methods.
• Java class hierarchy organizes all classes into a
single subclass and superclass relationship rooted
in Object.
• A class definition:
– header, which names the class and describes its use and
pedigree
– body , which contains its details.
• A pedigree describes where it fits in the Java class
hierarchy.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Summary: Key Points (cont)
• A class definition encapsulates the data and
methods needed to carry out the class’s task.
• Design Goals:
– Well-defined purpose
– Well-articulated (public) interface 
– Hidden implementation details (private state)
– General and Extensible.
• A boolean is a primitive type that can be true or false.
• Object interface: The public class elements
• Keyword: a term that has special meaning.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Summary: Key Points (cont)
• An identifier begins with a letter followed by any
number of letters, digits and the underscores (_)
and cannot be identical to a keyword.
• Field declaration (instance variable)
– reserves memory within the object
– associates a name and type with the location
– specifies its accessibility (public or private)
• Information Hiding: Instance variables should be
private.
• Identifier Scope: Where an identifier can be used.
• Class scope: Fields and methods can be used
anywhere in the class.
Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Summary: Key Points (cont)
• Method definition:
– Header: names the method and provides other general
information
– Body:  contains its executable statements.
• Methods that have a return type must return a
value of that type.
• Methods that don’t return a value should be
declared void.
• A method’s formal parameters  are variables that
are used to bring information into the method.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects
Summary: Key Points (cont)
• A qualified name is one which involves the dot
operator (.) and is used to refer to an object's
methods and instance variables.
• Declaring a reference  variable creates a name for
an object but doesn't create the object itself.
• Instantiating a reference  variable creates an
object and assigns the variable as its name or
reference.
• Execution of a Java application begins with the
first statement in the body of the main() method.

Java, Java, Java, 2E by R. Morelli Copyright 2002. All rights reserved. Chapter 2: Objects