Transcript lec0906

Review of OO
Introduction to Eclipse/Java
September 6, 2005
Object Oriented paradigm
An approach to the solution of problems in which all
computations are performed in the context of objects.
• The objects are instances of classes, which:
—are data abstractions
—contain procedural abstractions that operation on the
objects
• A running program can be seen as a collection of objects
collaborating to perform a given task
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
2
Procedural vs OO Design
main
Account
credit
debit
perform transaction
credit
debit
compute interest compute fees
if checking
if checking
then xxx
then xxx
if sav ings
if sav ings
then xxx
then xxx
etc.
etc.
© Lethbridge/Laganière 2001
CheckingAccount Sav ingsAccount
compute interest
compute f ees
Chapter 2: Review of Object Orientation
compute interest
compute f ees
3
2.2 Objects and Classes
Object
• A chunk of data in a running software system
—Member of a Java class
• Has properties that represent its state
—Has Java instance variables
• Has behaviour that defines how it can act and react
—Java methods
• Represented in UML by a named box with values assigned
A class:
• Represents objects that share the same properties and behavior
• Represented in UML by a named box
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
4
Example Objects
Jane:
date of birth: 1955/02/02
address: 99 UML St.
position: Manager
Greg:
Savings Account 12876:
balance: 1976.32
opened: 1997/03/03
date of birth: 1970/01/01
address: 75 Object Dr.
Margaret:
Mortgage Account 29865:
balance: 198760.00
opened: 2000/08/12
property: 75 Object Dr.
date of birth: 1980/03/03
address: 150 C++ Rd.
position: Teller
Transaction 487:
amount: 200.00
time: 2001/09/01 14:30
Instant Teller 876:
location: Java Valley Cafe
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
5
Classes vs Instances (Objects)
• Something should be a class if it could have instances
• Something should be an instance if it is clearly a single member of
the set defined by a class
Film
• Class; instances are individual films.
Reel of Film:
• Class; instances are physical reels
Film reel with serial number SW19876
• Instance of ReelOfFilm
Science Fiction
• Instance of the class Genre.
Science Fiction Film
• Class; instances include ‘Star Wars’
Showing of ‘Star Wars’ in the Phoenix Cinema at 7 p.m.:
• Instance of ShowingOfFilm
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
6
2.3 Instance Variables
Class variables that hold data present in each instance
• Attributes
—Simple data
—E.g. name, dateOfBirth
• Associations
—Relationships to other important classes
—E.g. supervisor, coursesTaken
—More on these in Chapter 5
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
7
Variables, Objects, and Methods
A variable References an object
• May refer to different objects at different points in time
Type of a variable
• Determines the class to which its referenced object
belongs
Method
• An abstraction that specifies a particular behaviour
• Independent of any code which implements that
behaviour
—E.g., calculating area (in general)
• Different classes can have methods with the same name
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
8
2.5 Organizing Classes: Inheritance
Hierarchies
Superclasses
Contain features common to a set of subclasses. I.e.,
every subclass is a special kind of its superclass (isa rule)
Inheritance hierarchies
• Show the relationships between superclasses and their
subclasses
—A UML triangle shows this relationship
—Java uses extends to implement this relationship
Inheritance
• The possession by a subclass of all the features (instance
variables and methods) defined in its superclass
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
9
An Example Inheritance Hierarchy
Account
SavingsAccount
© Lethbridge/Laganière 2001
ChequingAccount MortgageAccount
Chapter 2: Review of Object Orientation
10
The Isa Rule
Always check subclasses to ensure they obey the isa rule
• “A checking account is an account”
• “A town is a municipality”
• “An undergraduate is a student”
Should ‘State’ be a subclass of ‘Country’?
• No, it violates the isa rule:
“A state is a country” doesn’t make sense.
• Rather, a country has provinces as its parts.
—Thus, states are better modeled as a collection of
instance variables for a country
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
11
A possible inheritance hierarchy of
mathematical objects
MathematicalObject
Shape
Point
Shape2D
Matrix
Shape3D
Ellipse
Polygon
Line
Circle
Quadrilateral
Plane
Rectangle
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
12
Make Sure all Inherited Features Make
Sense in Subclasses
Account
balance
opened
creditOrOverdraftLimit
credit
debit
calculateInterest
SavingsAccount
ChequingAccount
highestChequeNumber
withdrawUsingCheque
calculateServiceCharge
© Lethbridge/Laganière 2001
MortgageAccount
collateralProperty
collateralValue
setCollateralValue
Chapter 2: Review of Object Orientation
13
Shape2D
2.6 Inheritance,
Polymorphism and
Variables
center
translate
getCenter
rotate
changeScale
getArea
getPerimeterLength
getBoundingRect
EllipticalShape
Polygon
semiMajorAxis
Circle
rotate
changeScale
getArea
getPerimeterLength
getBoundingRect
getRadius
© Lethbridge/Laganière 2001
getBoundingRect
getVertices
Ellipse
SimplePolygon
semiMinorAxis
orientation
rotate
changeScale
getArea
getPerimeterLength
getBoundingRect
getOrientation
getSemiMajorAxis
getSemiMinorAxis
getFocus1
getFocus2
ArbitraryPolygon
orientation
points
rotate
getOrientation
addPoint
remov ePoint
rotate
changeScale
getArea
getPerimeterLength
getVertices
Rectangle
RegularPolygon
height
width
numPoints
radius
changeScale
setHeight
setWidth
getArea
getPerimeterLength
getVertices
getBoundingRect
changeNumPoints
changeScale
getArea
getPerimeterLength
getVertices
Chapter 2: Review of Object Orientation
14
Some Operations in the Shape Example
Original objects
(showing bounding rectangle)
Rotated objects
(showing bounding rectangle)
T ranslated objects
(showing original)
Scaled objects
(50%)
Scaled objects
(150%)
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
15
Abstract Classes and Methods
Each method should be declared in the class at the
highest level in the hierarchy where it makes sense
• A method may be abstract (unimplementable) at that
level
—Java uses abstract to denote this
—If so, the class also becomes abstract
—No objects can be defined for an abstract class
• If a superclass has an abstract method then its
subclasses must implement that method at some level
—Leaf classes in the hierarchy must have no abstract
methods
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
16
Overriding
A non-abstract method can be redefined in a subclass
where it would normally be inherited.
• For restriction
—E.g. scale(x,y) would not work in Circle
• For extension
—E.g. SavingsAccount might charge an extra fee
following every debit
• For optimization
—E.g. The getPerimeterLength method in
Circle is much simpler than the one in Ellipse
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
17
An object is immutable if:
• Instance variables are initialized only when the object is
first created.
• None of the methods can change the values of an
instance variable
—E.g. a scale method could only create a new
object, not modify an existing one
• This is like a constant.
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
18
Dynamic binding
Occurs when decision about which method to run can
only be made at run time
• Needed when:
—A variable is declared to have a superclass as its
type, and
—There is more than one possible (polymorphic)
method that could be run for that type and its
subclasses
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
19
Java Concepts: Documentation
Looking up classes and methods is an essential skill
• Looking up unknown classes and methods will get you a
long way towards understanding code
Java documentation can be automatically generated by
a program called Javadoc
• Documentation is generated from the code and its
comments
• You should format your comments as shown in some of
the book’s examples
—These may include embedded html
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
20
Java Concepts: Arrays and Collections
Arrays are of fixed size and lack methods to manipulate them
Vector is the most widely used class to hold a collection of other
objects
• More powerful than arrays, but less efficient
Iterators are used to access members of Vectors
• Enumerations were formally used, but were more complex
v = new Vector();
Iterator i = v.iterator();
while(i.hasNext())
{
aMethod(v.next());
}
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
21
Java Concepts: Casting
Java 1.4 is very strict about types
• If a variable is declared with type X, you can only
invoke methods on it that are defined in class X or its
superclasses.
• If you know that a particular subclass is stored, then you
can cast the variable to the subclass
—E.g. if I know a Vector contains instances of
String, I can get the next element of its
Iterator using:
(String)iterator.next();
• Java 1.5 is more flexible in this regard (casting is often
automatic)
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
22
Java Concepts: Exceptions
Anything that can go wrong should result in the raising
of an Exception
•Exception is a class with many subclasses for specific
things that can go wrong
Use a try - catch block to trap an exception
try
{
// some code
}
catch (ArithmeticException e)
{
// code to handle division by zero
}
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
23
Java Concepts: Interfaces
Like abstract classes, but cannot have executable
statements
• Define a set of methods that are useful in several classes
A class can implement any number of interfaces
• It must implement all of the interface’s methods
You can declare the type of a variable to be an interface
• This is just like declaring the type to be an abstract class
Important interfaces in Java’s library include
•Runnable, Collection, Iterator,
Comparable, Cloneable
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
24
Java Concepts: Packages and Importing
A package combines related classes into a subsystem
• All the classes are placed in the same directory, which
names the package
• Each such class may have a header line identifying the
package to which it belongs:
package kk2Client;
• Importing all the classes in a package is specified in the
header line of a class file:
import finance.banking.accounts.*;
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
25
Java Concepts: Access control
Applies to methods and variables
•public
—Any class can access
•protected
—Only code in the package, or subclasses can access
• (blank)
—Only code in the package can access
•private
—Only code written in the class can access
—Inheritance still occurs!
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
26
Java Concepts: Threads and concurrency
Thread:
• A sequence of executing statements that can be
running concurrently with other threads
To create a thread in Java:
1. Create a class implementing Runnable or extending
Thread
2. Implement the run method as a loop that does
something for a period of time
3. Create an instance of this class
4. Invoke the start operation, which calls run
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
27
Java Concepts: Style Guidelines
Write readable code
• Always choose the simpler alternative
• Reject clever code that is hard to understand
• Shorter code is not necessarily better
• Avoid code duplication (make a new method and call it)
• Choose descriptive names (don’t worry about length)
Naming classes
• Use capital letters and singular nouns, E.g. BankAccount
• Use the right level of generality, E.g. Municipality, not City
• Make sure the name has one meaning, E.g. ‘bus’ a poor choice
Prefer private over public (information hiding)
Do not mix user interface code with non-user interface code
• Interact with the user in separate classes
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
28
Overview of Eclipse
•A general software design environment that:
—Supports Java
—Supports UML modeling
—Supports Java documentation
—Is highly flexible and adaptable to different languages
—Has extensive on-line tutorial and help information
Eclipse runs on OS X and Windows machines
—Freely downloadable
•Our lab version is Eclipse 3.0.1 (www.eclipse.org) with:
—Java 1.4 (java.sun.com)
—Omondo UML (www.omondo.com)
—JML (www.cs.iastate.edu/~leavens/JML/index.shtml)
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
29
Eclipse: Startup
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
30
Eclipse: Opening the workbench
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
31
Eclipse: Opening the Java Perspective
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
32
Eclipse: creating a new Java project
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
33
Eclipse: naming the project
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
34
Eclipse: Importing Java code into a project
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
35
Eclipse: Creating a run configuratioin
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
36
Eclipse: Running a program (thread)
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
37
Eclipse: Running another program (thread)
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
38
Eclipse: Switching between threads
© Lethbridge/Laganière 2001
Chapter 2: Review of Object Orientation
39