Programming in Java: OOP, Object, Class
Programming in Java: OOP, Object, Class
交通大學資訊工程學系
Java OOP-class
Outline
OOP programming Paradigm
Object, Class
Encapsulation and Information Hiding
Inheritance (extension) vs. Contain
Object-Oriented Technology: CRC, UML, . . .
The Life Cycle of an Object
Abstract Classes
Interface
Access Modifiers
Nested Class
Upcasting and Polymorphism
交通大學資訊工程學系 蔡文能 第 2頁
Java OOP-class
交通大學資訊工程學系 蔡文能 第 3頁
Java OOP-class
Programming Paradigms
Imperative Programming (FORTRAN, C, Pascal, …)
The most common programming paradigm
Functional Programming (LISP, …)
Logic Programming (Prolog)
(Declarative programming language; 宣告式語言 )
Object-Oriented Programming
(Smalltalk, C++, Java, …)
Simply using C++/Java constructs does not automatically
lead to well-organized Object-Oriented Programs.
交通大學資訊工程學系 蔡文能 第 4頁
Java OOP-class
Why OO Programming?
Better concepts and tools to model and represent the real
world as closely as possible (including concurrency, e.g., in
Windows GUI)
=> model of reality
=> behavior modeling
Better reusability & extensibility (inheritance)
=> reduce the time/cost of development
Enhanced maintainability & improved reliability –
“Encapsulation” and “Information Hiding”
Object only accessible through the external interface
Internal implementation details are not visible outside
Localized changes to implementation of classes
Completeness: all required operations are defined
Independent testing and maintenance
Help writing good program more easily
交通大學資訊工程學系 蔡文能 第 5頁
Java OOP-class
Objects
An object is a thing.
Example of Objects
John Mary 238-49-1357 Object name
Customer
Customer Dog
Dog Account
Account
Object
‘type’
交通大學資訊工程學系 蔡文能 第 6頁
Java OOP-class
Classes
A class (e.g., Dog) is a kind of mold or template to create objects (e.g.,
Mary and DooDoo)
mold = 模型 = mould
An object is an instance of a class. The object belongs to that class
Instance-of Mary
Dog Dog
Dog
Dog
DooDoo
Dog
Dog
Dog
交通大學資訊工程學系 蔡文能 第 7頁
Java OOP-class
What Is an Object?
These real-world objects all have states and behaviors.
Definition: An object is a software bundle of variables
and related methods (function).
A common visual
representation of a
software object.
交通大學資訊工程學系 蔡文能 第 8頁
Java OOP-class
Example: Bicycle
The software bicycle's current state:
its speed is 10 mph,
its pedal cadence is 90 rpm, and
its current gear is the 5th gear.
交通大學資訊工程學系 蔡文能 第 9頁
Java OOP-class
Object ( 物件 , 個體 ) -- 就是以前的變數
(Variable)
交通大學資訊工程學系 蔡文能 第 11頁
Java OOP-class
Encapsulation ( 封藏 )
Hide the object's nucleus from other objects in the program.
The implementation details can change at any time without affecting other
parts of the program.
It is an ideal representation of an object, but
For implementation or efficiency reasons, an object may wish to expose
some of its variables or hide some of its methods.
Benefits:
Modularity
The source code for an object can be written and maintained independently of
the source code for other objects.
Information hiding
An object has a public interface that other objects can use to communicate with
it.
Classes in Java
A class -- is a template that describes the data and behavior
associated with instances of that class.
An object -- instantiate a class you create an object.
An object is an instance of some class.
The data associated with a class or object is stored in
variables.
The behavior associated with a class or object is
implemented with methods.
Methods are similar to the functions or procedures in C.
Messaging
Three components comprise a message:
1. The object to whom the message is addressed (Your Bicycle).
2. The name of the method to perform (changeGears).
3. Any parameters needed by the method (lowerGear).
Benefits: yourBicycle.changeGears(lowerGear)
Message passing supports all interactions between objects.
Messages can be sent and received between processes in the same
machine or in different machines.
Object-Oriented Technology
Object-Oriented Analysis (OOA)
Goal: Understand the domain
Object-Oriented Design (OOD)
Goal: Design a solution, a model of the domain in which the
desired activities occur
Object-Oriented Programming (OOP)
Goal: Implement the solution
Note: A Good Design is 2/3 Before You Hit the Keyboard
emphases = 重點 = emphasis 的
複數
交通大學資訊工程學系 蔡文能 第 26頁
Java OOP-class
Object-Oriented Analysis
Step one: Brainstorming Candidate Classes
Write down all the objects that related
Focus on the nouns
Good objects have attributes and services
Now, filter the candidates
Deal with the interface later (Not part of the domain)
Are some candidates attributes of others?
Are some subclasses of others? (Inheritance)
Are some instances of others?
Object-Oriented Design
Step one: Create a UML class diagram of your
objects
Step two: Create a detailed description of the
services to be performed
Peter Coad's "I am a Count. I know how to
increment…"
Activity, sequence, or collaboration UML diagrams
amigos = friends
交通大學資訊工程學系 蔡文能 第 33頁
Java OOP-class
History of the UML( http://www.uml.org/ )
Approved 2004 UML 2.0
UML 12 Diagrams
Behavior : Structural:
Use Case Class
Sequence Component
Collaboration Deployment
State Chart Object
Activity
Model Management:
Packages (class diagram contains packages)
Subsystems (class diagram contains subsystems)
Models (class diagram contains models)
交通大學資訊工程學系 蔡文能 第 36頁
Java OOP-class
So, What is UML?
軟體工程師共通的語言
UML is a Unified Modeling Language
UML is a set of notations, not a single methodology
Modeling is a way of thinking about the problems using
models organized around the real world ideas.
Resulted from the convergence of notations from three
leading Object-Oriented methods:
Booch method (by Grady Booch)
OMT (by James Rumbaugh)
OOSE (by Ivar Jacobson)
You can model 80% of most problems by using about 20%
of the UML
SetTime
WatchUser
WatchRepairPerson
Use case
ChangeBattery
Attributes Operations
Activation Message
Transition button1Pressed
button1&2Pressed button2Pressed
Blink Increment
Minutes Minutes
button1Pressed
button1&2Pressed
button2Pressed
Stop Blink Increment
Blinking Seconds Seconds
Classes in UML
Classes describe objects
Behaviour (member function signature / implementation)
Properties (attributes and associations)
Association, aggregation, dependency, and inheritance
relationships
Multiplicity and navigation indicators
Role names
Objects described by classes collaborate
Class relations → object relations
Dependencies between classes
交通大學資訊工程學系 蔡文能 第 44頁
Visibility shown as
Java + OOP-class
public
UML Class -
#
private
protected
Class name
Data members
(attributes)
Instance methods
Class Attributes
Attributes are the instance data members
and class data members
Attribute
Class data members (underlined) Class name compartment
are shared between all instances
(objects) of a given class
Visibility shown as
+ public
- private
# protected
visibility name : type
Operations
Class methods (underlined)
compartment
can only access to class data
members, no need for a class
instance (object)
交通大學資訊工程學系 蔡文能 第 47頁
Java OOP-class
Template Classes
Type parameter(s)
Operations compartment
as usual, but may have
type parameter instead of
concrete type
Class Inheritance
Base class or super class
Recommended Book:
UML Distilled
Serious O-O designers DO use UML
UML Distilled by Martin Fowler is a great practical
introduction to UML
Official UML book series published by Addison-Wesley
http://www.omg.org
交通大學資訊工程學系 蔡文能 第 52頁
Java OOP-class
UML Tools
Most complete tool: Rational Rose,
http://www.rational.com
Lots of others
Together by Object International, http://www.oi.com
BOOST (Basic Object-Oriented Support Tool) by Noel Rappin,
available on CD/CoWeb
Argo-UML, ObjectPlant, Posiden, etc.
O O Features
Encapsulation Object
Information Hiding (Data Hiding) Based
Inheritance
Polymorphism For Software Reuse
Object Oriented
( 物件導向 )
( 個體導向 )
交通大學資訊工程學系 蔡文能 第 54頁
Java OOP-class
OO features
Encapsulation
Information Hiding
The concept of abstraction is
fundamental in programming
抽象化的概念以前
就有 : 函數 / 副程 Subprogram / function
式
增加 :
Inheritance
process abstraction
Polymorphism
ADT
Data abstraction
Software Reuse
交通大學資訊工程學系 蔡文能 第 55頁
Java OOP-class
Class elements
Constructors
};
int main( ) { 使用 default
Student x, m, n; constructor
Student y(456); // Error 沒有參數
x.setId(123);
return 0; Student y(456) ; 有問
} 題!
因為 default
交通大學資訊工程學系 蔡文能 第 62頁
constructor
Java OOP-class
Scope
Finalization
When freeing an object, the system will call this first.
The finalize method is a member of the Object class.
Implementing a finalize method to release resources that
aren't under the control of the garbage collector, such as native
peers.
Scenario: For a file object, when freed, need to close it.
Problem: Make the internal JVM implementation for
memory management very complicated.
Example
public class Rectangle {
public Point origin;
. . .
protected void finalize() throws Throwable {
origin = null;
super.finalize();
}
}
交通大學資訊工程學系 蔡文能 第 72頁
Java OOP-class
Overriding 不是
overloading !
交通大學資訊工程學系 蔡文能 第 74頁
Java OOP-class
Overloading
A Method's Name (function name)
Java supports method name overloading so that multiple methods can
share the same name.
class DataRenderer {
void draw(String s) { . . . }
void draw(int i) { . . . }
void draw(float f) { . . . }
}
Abstract methods
• Abstract methods are declared but do not contain an
implementation.
• For example, the MotorVehicle class may have an abstract
method gas( ):
public abstract class MotorVehicle {
private double speed, maxSpeed;
void accToMax( ) { speed = maxSpeed;} // 這個不是抽象函數 !
public abstract void gas( ); // 抽象函數 ; 在 C++ 是寫 =0; 的
函數
/* … */
}
• So MotorVehicle can NOT be instantiated
(ie., can not be used to create an object.)
交通大學資訊工程學系 蔡文能 第 77頁
Java OOP-class
Interfaces
Defines a set of methods that a class must implement
• An interface is like a class with nothing but abstract methods
and final and static fields (constants).
• An interface can also have fields, but the fields must be
declared as final and static.
• All methods are abstract implicitly.
Naming a Package
The name of the Rectangle class in the graphics package is
really graphics.Rectangle
The name of the Rectangle class in the java.awt package is
really java.awt.Rectangle
Convention
com.company.package
com.company.region.package
Access Modifiers
(no keyword): class/package access (different from C++)
I.e., package available
public: world access (same as C++)
private: class access (same as C++)
protected: subclassing access(same as C++)
Comparisons
注意西方人是打 X 表示勾選 !
Static
static:
only one copy for the class and all instances
Usually used as a global variable (even no instances)
class TestStatic {
int x, y, z;
int average() {return (x+y+z)/3; }
static int j = 0;
static int peek() { Static variable
Stati j += 2; j,k
x = 3; // error!
c } Static block
metho static int k = peek();
d static { j = j*5; } // done when loading class
public static void main(String[] args) {
...
TestStatic ts = new TestStatic();
int ave = ts.average();
... Static method
}
}
Final
Final variables:
The value of a final variable cannot change after it has been
initialized.
Such variables are similar to constants in other programming
languages.
final Color red = Color.red;
A final local variable that has been declared but not yet initialized is
called a blank final.
final int blankfinal;
. . .
blankfinal = 0;
Nested Class
A nested class is a class that is a member of another class.
class EnclosingClass{
. . .
class ANestedClass {
. . .
}
}
Define a class within another class when the nested class
makes sense only in the context of its enclosing class.
For example, a text cursor makes sense only in the context of a
particular text component.
A nested class has a special privilege:
It has unlimited access to its enclosing class's members, even for
private.
Just like a method that can access private.
Example: Adaptor
Using an Inner Class to Implement an Adapter
import java.util.Enumeration;
import java.util.NoSuchElementException;
public class Stack {
private java.util.Vector items;
Anonymous Class
You can declare an inner class without naming it.
Example: (Rewrite the previous slide.)
public class Stack {
private Vector items;
...//code for Stack's methods and constructors not shown...
public Enumeration enumerator() {
return new Enumeration() {
int currentItem = items.size() - 1;
public boolean hasMoreElements() {
return (currentItem >= 0);
}
public Object nextElement() {
if (!hasMoreElements())
throw new NoSuchElementException();
else
return items.elementAt(currentItem--);
}
};
}
}
}
Circle Square Triangle
class Circle extends Shape { draw() draw() draw()
erase() erase() erase()
void draw( ) {
System.out.println("Circle.draw( ) ");
}
void erase( )
{System.out.println("Circle.erase( )");}
交通大學資訊工程學系 蔡文能 第 99頁
}
Java OOP-class
謝謝捧場
http://www.csie.nctu.edu.tw/~tsaiwn/course/java/
蔡文能
交通大學資訊工程學系 蔡文能 第 104頁