Professional Documents
Culture Documents
01 OOP Concepts
01 OOP Concepts
July 2012
1
Object
Class
Inheritance
Interface
Package
What is an object?
Software objects are often used to model the real-world objects that you
find in everyday life.
Real-world objects share two characteristics: they all have state and
behavior. For example:
Dogs have state (name, color, breed) and behavior (barking, fetching,
wagging tale).
Bicycles also have state (current gear, current pedal cadence, current
speed) and behavior (changing gear, changing pedal cadence, applying
brakes).
4
Identify the state and behavior for real-world objects is a good way to
begin thinking in terms of OOP.
Exercise 1:
Observe the real-world objects that are in your immediate area, for
each object that you see, ask yourself two questions:
Your desktop lamp has only two possible states (on, off) and two
possible behaviors (turn on, turn off).
Your desktop radio might have additional states (on, off, current
volume, current station) and behaviors (turn on, turn off, increase
volume, decrease volume, seek, scan, tune).
1. Modularity
2. Information hiding
3. Code re-use
10
Modularity:
Information hiding:
11
Code re-use:
Object
Class
Inheritance
Interface
Package
13
Each bicycle was built from the same set of blueprints and contains
the same components.
What is a class?
void printStates() {
System.out.println("cadence:" + cadence + " speed:" + speed + " gear:"
+ gear);
}
}
15
Its just the blue print for bicycles that might be used in an
application.
16
bike2.changeCadence(50);
bike2.speedUp(10);
bike2.changeGear(2);
bike2.changeCadence(40);
bike2.speedUp(10);
cadence:50 speed:10 gear:2
bike2.changeGear(3);
bike2.printStates(); cadence:40 speed:20 gear:3
}
}
17
Object
Class
Inheritance
Interface
Package
18
Each kind also defines additional features that make them different:
20
21
Object
Class
Inheritance
Interface
Package
22
Recall: objects define their interaction with the outside world through
their methods.
The buttons on the front of your television set are the interface
between you and the electrical wiring on the other side of its plastic
casing.
You press the power button to turn the television on and off.
23
Implement an interface:
class MyBicycle implements IBicycle {
// remainder of this class
// implemented as before
}
Note that MyBicycle must implement all methods defined by the
interface IBicycle (as in Bicycle).
24
Object
Class
Inheritance
Interface
Package
25
http://docs.oracle.com/javase/7/docs/api/index.html
26
Exercise 2: Create new classes for each real-world object that you
observed.
Exercise 3: For each new class that you have created above:
Create an interface that defines its behavior, then require your class
to implement it.
Omit one or two methods and try compiling. What does the error
look like?
27