Programming with Objects
Intro to object-orientation and how to use objects in Java
James Brucker
The Realities of Software
Useful, real-world software
1. Change
2. Complexity
The Problem
"Programming is fun, but developing quality software is
hard. In between the nice ideas, the requirements or
the "vision", and a working software product, there is
much more than programming.
Analysis and design, defining how to solve the problem,
what to program, capturing this design [...], review,
implement, and evolve is what lies in the core of this
book."
[Forward to Larman, Applied UML and Patterns, 3E. Forward by Philipe Kruchten (IBM Rational)]
Intrinsic Complexity of Software
About the future of software development...
"There is no single development, in either technology or
in management technique, that by itself promises even
one order of magnitude improvement in productivity, in
reliability, in simplicity."
"No Silver Bullet" by Frederick Brooks. Computer, 1987
See also page 5-6 for Brooks comments about object-oriented approach.
Miller’s Law
At any one time, a person can concentrate on at most 7 2 chunks (units of information)
To handle larger amounts of information, use stepwise refinement
Concentrate on the aspects that are currently the most important
Postpone aspects that are currently less critical Every aspect is eventually handled, but in order of
current importance
This is an incremental process
Benefit of Object-Orientation (1)
Encapsulate complexity
divide program into classes
each class has its own responsibilities and data
class has only one purpose
class has simple interface
hide implementation details
Benefit of Object-Orientation (2)
Encapsulate change
each class presents only a simple public interface
class hides implementation details
as a result...
we can localize the effect of change
Benefit of Object-Orientation (3)
Reuse code
classes are reusable
polymorphism lets us interchange parts
inheritance lets us build new classes that reuse code from old classes.
Benefit of Object-Orientation (4)
Better abstraction
objects make good models for things in the real world (problem domain)
let us think about the problem instead of the code
simplify the problem so we can think about problem without too many details
Objects and Programs
An OO program consists of objects that interact with each other.
Classes
A class is a blueprint or definition for a kind of object.
A class defines the attributes and behavior of objects.
Cat
birthday
color
sex
sleep( )
eat( Food )
play( )
chase( Object )
attributes are characteristics of objects. In Java: variables, "fields"
behavior is what the object can do. In Java: methods
Objects
Objects are instances of a class.
In Java, to create a new object use "new", e.g.
Cat somecat = new Cat( );
create the object in memory
invoke the constructor of Cat class to initialize values.
Object creation can use values, too:
Cat kitten = new Cat( Color.BLACK, "male", ... );
3 Fundamental Characteristics of Objects
Objects have: state - the current condition of an object behavior - the actions or messages an object can
accept identity - every object is distinguishable, even if two
objects have the same state
How to use the methods of an object:
// call a method in the same object:
turnLeft( );
canMove( );
Bank Account Example BankAccount class is the definition for bank accounts.
class name: BankAccount
attributes: accountNumber, name, balance
behavior: getBalance( ), credit(amount), debit(amount), getName( )
BankAccount
name: StringaccountNumber: Stringbalance: double
<<constructor>>
BankAccount( name )
getBalance( )credit(amount: double )debit( amount: double)getName( )
UML class diagram
Bank Account Object
An object is an actual instance of the class. rich is a bank accoount
Example:
BankAccount rich =
new BankAccount("Taksin Shinawat" );
rich.credit( 2000000000 );
rich.credit( 1000000000 );
// needs money to buy a football team...
rich.debit( 500000000 );
// does he have enough to buy Hawaii?
rich.getBalance( ) ; // = 2,500,000,000
rich: BankAccount
name = Taksin ShinawataccountNumber = 000001balance = 250000000
getBalance( )credit(double amount)debit(double amount)getName( )
UML object diagram
Object Properties
Example:
For the "rich" object, what are...
state?
behavior?
identity?
HondaCivic Example
The definition of a HondaCivic consists of: specifications design documents blue prints list of parts list of qualified suppliers instructions for assembly inspection procedure and check lists operating instructions maintenance manual and procedures
HondaCivic class
But, the Honda Civic owner doesn't need to know all these details. He needs to know about a Honda Civic's properties (public attributes) and behavior.
For example (simplified):HondaCivic
bodyStylebodyColortrimColorengineSizedoorstransmissionType
turnLeft( )turnRight( )brake( )accelerate( )isEngineOn( )fuelAmount( )
properties(attributes)
behavior
Buying A Honda Civic
You go to the Honda dealer and say...
I want aHonda Civic Yes, sir. This
way, please...
Buying A Honda Civic (2)
the dealer offers you the class for a Honda Civic...
Here you are! All the documents and blue prints for a Honda Civic.
... that will be 1,000,000,000 Baht, please.
Construction and operation of a Honda Civic: complete documents.
Buying A Honda Civic (3)
but you can't drive blue prints and documents
That's not exactly what I had in mind. I want a car I can drive...
I see... you want an instance of Honda Civic -- a Honda Civic object.
Buying A Honda Civic (4)
Silver, 4 door, automatic transmission, tinted windows, ...
yourcar : HondaCivic
bodyStyle = sedanbodyColor = silvertrimColor = silverengineSize = 1600ccdoors = 4transmissionType = auto
turnLeft( )turnRight( )brake( )accelerate( )isEngineOn( )fuelAmount( )
yourcar = new HondaCivic("silver", 4door, automatic,... );
attributes
behavior
Review: Class versus Objects
HondaCivic
Defines the properties and behavior for all instances (objects) of this class.
Specific realization of the class
Object Identity Example Primitive data types don't have identity. You cannot distinguish two primitives when the values are same.
primitive variables represent values not objects
double x = 10;
double y = 10;
if ( x == y ) System.out.print("same"); // true
Object Identity Example
Objects do have identity. You can distinguish two objects even when the values
are the same. object variable is a reference to an object
Double x = new Double(10);
Double y = new Double(10);
if ( x == y ) System.out.print("same"); // false
Object Identity Example (2)
Two Honda Civic cars can be distinguished even if they exactly the same features and same state (brand new)
!=
Second Program
/** Print an impersonal greeting message * @author James Brucker */public class Greeting {
private String who;/** constructor for new objects */public Greeting( String name ) {
who = name; // save the name}public void sayHello( ) {
System.out.println("Hello, "+who);}public void sayGoodbye( ) {
System.out.println("Goodbye, "+who);
}}
Any text placed inside /* .... */is ignored by the compiler.
This is a Javadoc comment.
An attribute of this class.
Each object will have a variable named "who" that contains data unique to each object (instance) of this class.
An attribute is a property of an object -- information the object uses to do its job.
Constructor for Objects
/** Print an impersonal greeting message * @author James Brucker */public class Greeting {
private String who;/** constructor for new objects */public Greeting( String name ) {
who = name; // save the name}public void sayHello( ) {
System.out.println("Hello, "+who);}public void sayGoodbye( ) {
System.out.println("Goodbye, "+who);
}}
A constructor for the class.
The constructor is a method that is called when a new object is created.
A constructor usually initializes the attributes of an object, but does not return any value ... not even a void.
Methods define Behavior
/** Print an impersonal greeting message * @author James Brucker */public class Greeting {
private String who;/** constructor for new objects */public Greeting( String name ) {
who = name; // save the name}public void sayHello( ) {
System.out.println("Hello, "+who);}public void sayGoodbye( ) {
System.out.println("Goodbye, "+who);
}}
A method of the class.
Methods can access the attributes of the object that they belong to.This method uses the who attribute. The value of who was set by the constructor.
Methods are the actions that an object can perform.Methods define behavior or responsibilities of objects.
Another method
/** Print an impersonal greeting message * @author James Brucker */public class Greeting {
private String who;/** constructor for new objects */public Greeting( String name ) {
who = name; // save the name}public void sayHello( ) {
System.out.println("Hello, "+who);}public void sayGoodbyte( ) {
System.out.println("Goodbye, "+who);
}}
Another method of the class.
No main method!
Creating Greeting Objects
/** Test the Greeting class. */public class TestGreeting {
public static void main(String[] args) {Greeting a = new
Greeting("John");Greeting b = new
Greeting("Nok");a.sayHello( );b.sayHello( );b.sayGoodbye( );a.sayGoodbye( );
}}
Create a Greeting object.
Create another Greeting object.
We'll create a separate "test" class (in its own file) that creates and uses Greeting objects.
Sending a Message to an Object
/** Test the Greeting class. */public class TestGreeting {
public static void main(String[] args) {Greeting a = new
Greeting("John");Greeting b = new
Greeting("Nok");a.sayHello( );b.sayHello( );b.sayGoodbye( );a.sayGoodbye( );
}}
Invoke sayHello method of the objects.
Output:
Hello, John.
Hello, Nok.
Goodbye, Nok.
Goodbye, John.
Notice that each object remembers its own attributes.
In object-oriented speaking, people say "we send a message to an object" to ask it to do something..
Sending messages
TestGreeting
Greetingcreate
sayHello( )
sayGoodbye( )
3 Fundamentals of Object-Oriented Paradigm
Encapsulation - a class includes both the data and operations that operate on the data. It can hide the implementation details.
A user of the class only sees the public interface.
Polymorphism - many classes can perform the same behavior and we can use them interchangably.
Inheritance - one class can build on top of another class and inherit all its methods and attributes.
Examples