0% found this document useful (0 votes)
88 views

Programming in Java: OOP, Object, Class

The document discusses object-oriented programming concepts in Java including objects, classes, encapsulation, inheritance, and polymorphism. It provides examples of how classes define objects in Java through templates that contain variables and methods. Inheritance allows subclasses to inherit features from parent classes to achieve code reuse. The document is intended to teach programming in Java using object-oriented principles.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views

Programming in Java: OOP, Object, Class

The document discusses object-oriented programming concepts in Java including objects, classes, encapsulation, inheritance, and polymorphism. It provides examples of how classes define objects in Java through templates that contain variables and methods. Inheritance allows subclasses to inherit features from parent classes to achieve code reuse. The document is intended to teach programming in Java using object-oriented principles.
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 104

Programming in Java

OOP, Object, Class


蔡文能
交通大學資訊工程學系
[email protected]

交通大學資訊工程學系
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

The Object-Oriented (OO) Programming


Paradigm

Object-Oriented Programming (OOP) is one of the


programming paradigms ( 典範 ) in computer science

OOP is the dominant moden programming paradigm

Object-Oriented Programming is well-known in the


business world by the name of ‘Object Technology’
Technology

交通大學資訊工程學系 蔡文能 第 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.

The software bicycle would also have methods to


 brake,
 change the pedal cadence, and
 change gears.

交通大學資訊工程學系 蔡文能 第 9頁
Java OOP-class

What Are Classes?


Definition:
 A class is a blueprint or prototype
Defines the variables and methods common to all objects of a
certain kind.
The Benefits of Classes
 Reusability -- Software programmers use the same class, and the
same code to create many objects.

交通大學資訊工程學系 蔡文能 第 10頁


Java OOP-class

Objects vs. Classes


Objects:
 E.g., a real car.
Classes: or types
 E.g., BMW-500

A Class is a blueprint or template of some


objects
Object is an Instance of some class.

Object ( 物件 , 個體 ) -- 就是以前的變數
(Variable)
交通大學資訊工程學系 蔡文能 第 11頁
Java OOP-class

ADT --- Data Abstraction


An Abstract Data Type (ADT) is a user-defined data type that
satisfies the following two conditions: (Encapsulation +
Information Hiding)
 The representation of, and operations on, objects of the type are
defined in a single syntactic unit; also, other program units can
create objects of the type.
 The representation of objects of the type is hidden from the
program units that use these objects, so the only operations
(methods) possible are those provided in the type's definition
which are known as interfaces.

ADT: 抽象資料型態 = 把資料以及對資料做處理


的操作 (function) 一起封藏在一個程式單

交通大學資訊工程學系 蔡文能 第 12頁
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.

交通大學資訊工程學系 蔡文能 第 13頁


Java OOP-class

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.

交通大學資訊工程學系 蔡文能 第 14頁


Java OOP-class

Class Bicycle in Java


Not allowed in C++
Language

public class Bicycle {


private int speed = 10;
private int pedalCadence = 90;
private int currentGear = 5;
// a constructor!
public void brake() { /* ... */ }
public void changePedalCadence(int x) { /* */ }
public void changeGear(int x) { /* ... */ }
}

交通大學資訊工程學系 蔡文能 第 15頁


Java OOP-class

Class HelloWorld (Applet version)


inherit Applet
import java.applet.Applet;
import java.awt.Graphics;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello world!", 50, 25);
}
}

交通大學資訊工程學系 蔡文能 第 16頁


Java OOP-class

What Is Inheritance? (extends)


Subclasses inherit variables and methods from superclasses.
 States:
Gear & Speed
 Behaviors:
Brake & Accelerate
Subclasses can
 Add variables and methods.
 Override inherited methods.
Benefits:
 Provide specialized behaviors
 Reuse the code in the superclass
 Abstract classes -- define "generic" behaviors.

交通大學資訊工程學系 蔡文能 第 17頁


Java OOP-class

Mankind extends Animal


public class Animal {
private int height = 0;
private int weight = 0;
Should public void talk( ) { System.out.println(“Arhh");}
be in }
different
files public class Mankind extends Animal {
private int iq = 120;
public void talk( ) { System.out.println("Hello");}
}

One Java file can only have one public class

Mankind is-a Animal


交通大學資訊工程學系 蔡文能 第 18頁
Java OOP-class

Mankind inherits Animal (C++)


class Animal {
int height = 0;
int weight = 0;
public:
Classes void talk( ) { System.out.println("Won");}
can be };
in same
class Mankind :public Animal {
file private: int iq = 120;
public: void talk( ) { System.out.println("Hello");}
} ;

In C++, ";" is required to terminate a class


交通大學資訊工程學系 蔡文能 第 19頁
Java OOP-class

Rectangle Contains Point


public class Point {
private int x = 0;
private int y = 0;
Should }
be in
different public class Rectangle {
private int width = 0;
files private int height = 0;
private Point origin = new Point();
}

Car has-a Wheel


交通大學資訊工程學系 蔡文能 第 20頁
Java OOP-class

Point and it's constructor

public class Point {


private int x = 0;
private int y = 0;
// a constructor!

this.x public Point(int xxx, int y) { this.y


x = xxx;
this.y = y;
}
}
. . .
Point p = new Point(44,78);

交通大學資訊工程學系 蔡文能 第 21頁


Java OOP-class

Class may have many Constructors


public class Rectangle {
int width = 0;
int height = 0;
Point origin;
// four constructors
public Rectangle() { origin = new Point(0, 0); }
public Rectangle(Point p) { origin = p; }
public Rectangle(int w, int h) { this(new Point(0, 0), w, h); }
public Rectangle(Point p, int w, int h)
{ origin = p; width = w; height = h; }

// a method for moving the rectangle


public void move(int x, int y) { origin.x = x; origin.y = y; }
// a method for computing the area of the rectangle
public int area() { return width * height; }
}

交通大學資訊工程學系 蔡文能 第 22頁


Java OOP-class

What Are Messages?


Message in an object.
Software objects interact and communicate with each other
by sending messages to each other.

When object A wants object B to


perform one of B's methods, object
A sends a message to object B.

交通大學資訊工程學系 蔡文能 第 23頁


Java OOP-class

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.

交通大學資訊工程學系 蔡文能 第 24頁


Java OOP-class

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

交通大學資訊工程學系 蔡文能 第 25頁


Java OOP-class

It's a process, not a waterfall


Design is an iterative activity
 Start in OOA, go to OOD, forget something in OOA
 Get to OOP, realize you didn't understand something and go back
The stages are there to identify emphases
 For example, OOA is TOTALLY Language-Independent

Waterfall model 是早期軟工強掉的軟體發展過程

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?

交通大學資訊工程學系 蔡文能 第 27頁


Java OOP-class

OOA: CRC Cards


Step two: Write CRC cards and work through scenarios
 Class-Responsibility-Collaborator Cards (Cunningham and Beck)
 Just 3x5 cards

•Although CRC is not


part of UML, they
add some very useful
insights throughout a
development.

Data fields (attributes) 寫


交通大學資訊工程學系 蔡文能 在背面 第 28頁
Java OOP-class

How to use CRC Cards


Make one for each candidate class
Invent scenarios: What should these objects do?
Play the cards
 Lay down the card that starts the scenario
 Write down its responsibility
 Add collaborator objects to help with that responsibility
 Pick up cards as they leave the scenario

交通大學資訊工程學系 蔡文能 第 29頁


Java OOP-class

Why CRC Cards?


Help you identify objects and their responsibilities
Help you understand interactions between objects
Cards form a useful record of early design activity
Cards work well in group situations and are understandable by
non-technical stakeholders

交通大學資訊工程學系 蔡文能 第 30頁


Java OOP-class

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

交通大學資訊工程學系 蔡文能 第 31頁


Java OOP-class

MDA-Model Driven Architecture?


A New Way to Specify and Build Systems
 2001 年由 OMG 制定的新開發架構 (http://www.omg.org)
 以 UML Model( 塑模 ) 為基礎
 支援完整開發週期 : Analysis, Design, Implementation,
Deployment, Maintenance, Evolution & Integration with later
systems ( 改進與後續整合 )
 內建協同運作性及跨平台性
 降低開發初期成本及提高 ROI ( 投資報酬 )
 可套用至你所使用的任何環境 :
Programming language  Network
Operating System  Middleware

交通大學資訊工程學系 蔡文能 第 32頁


Java OOP-class

Unified Modeling Language


http://www.omg.org http://www.UML.org
There have been O-O gurus for many years
Three of them worked together to define UML (“Three
amigos”: Booch, Rumbaugh, Jacobson)
Has now been approved as a standard by the Object
Management Group (OMG)
Very powerful, many forms of notation
 It's even provable! (with OCL) (Object Constrain Language)

amigos = friends
交通大學資訊工程學系 蔡文能 第 33頁
Java OOP-class
History of the UML( http://www.uml.org/ )
Approved 2004 UML 2.0

Minor revision 2003 UML 1.5

Minor revision 2001 UML 1.4


Public
Feedback Minor revision 1999 UML 1.3
OMG Acceptance, Nov 1997
Final submission to OMG, Sept 1997 UML 1.1
First submission to OMG, Jan 1997
UML partners UML 1.0

Web - June 1996 UML 0.9


OOPSLA 95 Unified Method 0.8

交通大學資訊工程學系 蔡文能 第 34頁


Other methods OOSE Booch method OMT
Java OOP-class

UML 常用的 Diagrams

Use case diagrams


 Functional behavior of the system as seen by the user.
Class diagrams
 Static structure of the system: Objects, Attributes, and
Associations.
Activity diagrams
 Dynamic behavior of a system, in particular the workflow, i.e. a flowchart.
Sequence diagrams
 Dynamic behavior between actors and system objects.
Statechart diagrams
 Dynamic behavior of an individual object as FSM ( 有限狀態機 ).

交通大學資訊工程學系 蔡文能 第 35頁


Java OOP-class

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

UML is a “blueprint” for building complex software


交通大學資訊工程學系 蔡文能 第 37頁
Java OOP-class

UML Core Conventions


Higraphs are an
Rectangles are classes or instances extension to the
Ovals are functions or use cases familiar Directed
Types are denoted with non-underlined names Graph structure
 SimpleWatch where nodes are
 Firefighter connected by
edges to other
Instances are denoted with an underlined names
nodes. Nodes
 myWatch:SimpleWatch
represent entities
 Joe:Firefighter in some domain (in
Diagrams are higraphs our case, classes,
 Nodes are entities (e.g. classes, states) packages,
 Arcs are relationships among entities (e.g. sender/receiver) methods, etc.).
 Containment represents belonging (e.g. use cases in package)

交通大學資訊工程學系 蔡文能 第 38頁


Java OOP-class
Use Case Diagram examples
A use case documents the
Package interaction between the
SimpleWatch system user and the system.
It is highly detailed in
Actor describing what is required
but is free of most
implementation details and
ReadTime constraints.

SetTime
WatchUser
WatchRepairPerson

Use case
ChangeBattery

Use case diagrams represent the functionality of the system


from user’s point of view. ( 強調 what, 但暫不管 how)
交通大學資訊工程學系 蔡文能 第 39頁
Java OOP-class

Class Diagram : a simple Watch


Class
Multiplicity
SimpleWatch Association
1 1 1 1
2 1 2 1
PushButton LCDDisplay Battery Time
state blinkIdx load() now()
push() blinkSeconds()
release() blinkMinutes()
blinkHours()
stopBlinking()
referesh()

Attributes Operations

Class diagrams represent the structure of the domain or system

交通大學資訊工程學系 蔡文能 第 40頁


Java
Sequence Diagram OOP-class
Object

:WatchUser :SimpleWatch :LCDDisplay :Time


pressButton1( blinkHours()
)
pressButton1() blinkMinutes()
pressButton2() incrementMinutes()
Activation
refresh()
pressButtons1And2() commitNewTime()
stopBlinking()

Activation Message

Sequence diagrams represent the behavior as interactions


It shows sequence of events for a particular use case

Object diagram with


numbered messages
Sequence numbers of messages
are nested by procedure call
交通大學資訊工程學系 蔡文能
Collaboration Diagram 第 41頁
Java
State chart Diagrams for the watch
OOP-class

Event Initial state State


button1&2Pressed button2Pressed
Blink Increment
Hours Hours

Transition button1Pressed

button1&2Pressed button2Pressed
Blink Increment
Minutes Minutes

button1Pressed
button1&2Pressed
button2Pressed
Stop Blink Increment
Blinking Seconds Seconds

Final state FSM: Finite State Machine


交通大學資訊工程學系 蔡文能 第 42頁
Java OOP-class
Activity Diagrams
An activity diagram shows flow control within a system
Handle Document Archive
Incident Incident Incident

An activity diagram is a special case of a state chart diagram in


which states are activities (“functions”)
Two types of states:
 Action state:
Cannot be decomposed any further
Happens “instantaneously” with respect to the level of abstraction used in the
model
 Activity state:
Can be decomposed further
The activity is modeled by another activity diagram

描述 Business process 或 use case 的操作流程 ; 像流程圖


交通大學資訊工程學系 蔡文能 第 43頁
Java OOP-class

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 method (static) Return types


Arguments
Data members, arguments and methods are specified by
visibility name : type
交通大學資訊工程學系 蔡文能 第 45頁
Java OOP-class

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

Data types shown after ":"

Visibility shown as
+ public
- private
# protected
visibility name : type

交通大學資訊工程學系 蔡文能 第 46頁


Java OOP-class

Class Operations (Interface)

Operations are the class


methods with their argument
and return types

Public (+) operations define the


class interface

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

Generic classes depending on parametrised types


交通大學資訊工程學系 蔡文能 第 48頁
Java OOP-class

Class Inheritance
Base class or super class

Arrow shows direction


of dependency (B inherits A)

Derived class or subclass

→ B inherits A's interface,


behaviour and data members
→ B can extend A, i.e. add new
data members or member functions
→ B depends on A,
A knows nothing about B
交通大學資訊工程學系 蔡文能 第 49頁
Java OOP-class

Multiple Inheritance (Java)

The derived class inherits


interface, behaviour and
data members of all its
base classes
implements
Extension and overriding
extends works as before

B implements the interface A and


is also a "countable" class since it
inherits class Countable

class B extends Countable implements A { /*…*/ }


交通大學資訊工程學系 蔡文能 第 50頁
Java OOP-class

How can two classes be related?


Generalization-specialization or IsA
 NamedBox IsA Box
 Diagram: Triangle on the relationship line
Association or HasA
 Box HasA Pen
 Diagram: Just a relationship line
 Aggregation is a part-whole relationship
Diagram: Diamond on the line
Dependency or TalksTo
 Dependency is sort of temporary HasA
Diagram: Dashed line in UML

交通大學資訊工程學系 蔡文能 第 51頁


Java OOP-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.

交通大學資訊工程學系 蔡文能 第 53頁


Java OOP-class

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

交通大學資訊工程學系 蔡文能 第 56頁


Java OOP-class

Constructors

For purpose of initialization objects have special


methods called constructors.
To write a constructor you must adhere to two rules :
1. The method name must exactly match the class
name.
2. There must not be a return type declared for the
method.

Java has NO destructor.


交通大學資訊工程學系 蔡文能 第 57頁
Java OOP-class

The Default Constructor

Every class has a constructor.


If you don’t write one Java provides one for you. This
constructor takes no arguments and has an empty body.

? What If you write one constructor ?

交通大學資訊工程學系 蔡文能 第 58頁


Java OOP-class
Struct – 自訂資料型別 in C/C++
#include <stdio.h> Why using struct ?
struct Student {
long sid;
Java has no struct
char name[9]; /* 四個 Big5 中文 */
float score[13]; /* 最多修 13 科 */
}; /* 注意 分號 */
int main( ) {
struct Student x; /* C++ 和 C99 不用寫 struct */
x.sid = 123;
strcpy(x.name, " 張大千 ") ; /* 注意 */
/* 用 loop 把成績讀入 x.score[?] */
}
交通大學資訊工程學系 蔡文能 第 59頁
Java OOP-class

Struct vs. Class in C++ (1/2)


#include <iostream.h>
class Student { // 若改為 struct Student { …?
long sid;
};
int main( ) {
privat
Student x; e
x.sid = 123; // compile 錯 , access not allowed
cout << "== " << x.sid << endl; // compile 錯
return 0;
}

交通大學資訊工程學系 蔡文能 第 60頁


Java OOP-class

Struct vs. Class in C++ (2/2)


#include <iostream.h>
class Student { // private:
long sid;
public: showNumber( ) { return sid; }
setId( long xx) { sid = xx; }
};
int main( ) {
Student x, y;
x.setId(123); // OK, 透過 public function setId( )
cout << " == " << x.showNumber( ) << endl; // OK
return 0;
}

交通大學資訊工程學系 蔡文能 第 61頁


Java OOP-class

Class(Object) Constructor 1/4 (C++)


#include <iostream.h>
class Student { // private:
long sid;
public: showNumber( ) { return sid; }
setId( long xx) { sid = xx; }

};
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

Class(Object) Constructor 2/4 (C++)


#include <iostream.h>
class Student { // private:
long sid;
public: showNumber( ) { return sid; }
setId( long xx) { sid = xx; }
Student(long x) { sid = x; }
加入這
};
constructor
int main( ) { Student x; 有問題 !
Student x; // Error 因為 default
Student y(456); // OK now constructor 不能用了
x.setId(123); –
return 0; 有兩種解決方法 :
} Student y(456) ; 現在 OK

交通大學資訊工程學系 蔡文能 第 63頁
Java OOP-class

Class(Object) Constructor 3/4 (C++)


#include <iostream.h>
class Student { // private:
long sid;
public: showNumber( ) { return sid; }
setId( long x) { sid = x; }
Student(long x=0) { sid = x; }
};
int main( ) {
Student x, y(456); // OK
x.setId(123);
Student x; 有問題
return 0;
解決方法一
}
使用 Default 參數

交通大學資訊工程學系 蔡文能 第 64頁


Java OOP-class

Class(Object) Constructor 4/4 (C++)


#include <iostream.h>
class Student { // private:
long sid;
public: showNumber( ) { return sid; }
setId( long xx) { sid = xx; }
Student(long x) { sid = x; cout << "Hehehe\n"; }
Student( ) { sid=0; cout << "Haha\n"; }
};
int main( ) {
Student x, y(456); // OK
x.setId(123);
Student x; 有問題
return 0;
}
解決方法之二
再加一個沒參數的
交通大學資訊工程學系 蔡文能 constructor 第 65頁
Java OOP-class

More about Classes


Properties:
 Single implementation inheritance - extends
The inherited class is called “superclass”.
 Multiple interface inheritance - implements
All classes inherit from java.lang.Object
Scope: (next slide)

交通大學資訊工程學系 蔡文能 第 66頁


Java OOP-class

Scope

交通大學資訊工程學系 蔡文能 第 67頁


Java OOP-class

The Life Cycle of an Object – Creation (I)


Creating Objects
Rectangle rect = new Rectangle();
 Declaring an Object
Object declarations can also appear alone :
Rectangle rect;
In Java, classes and interfaces can be used as data types.
Declarations do not create new objects.
 Instantiating an Object
The new operator allocates memory for a new object.
The new operator requires a argument: a call to a constructor.
The new operator creates the object, and the constructor initializes it.
new Rectangle(100, 200);
The new operator returns a reference to the newly created object.
Rectangle rect = new Rectangle(100,200);
After this statement, rect refers to a Rectangle object.
交通大學資訊工程學系 蔡文能 第 68頁
Java OOP-class

The Life Cycle of an Object -- Creation (II)


 Initializing an Object
Constructors have the same name as the class and have no return
type.
public Rectangle(Point p)
public Rectangle(int w, int h)
public Rectangle(Point p, int w, int h)
public Rectangle()
Example:
Rectangle rect = new Rectangle(100, 200);
Rectangle rect = new Rectangle(
new Point(44,78));

A constructor can takes no arguments, is called a no-argument


constructor.
If a class does not define any constructors, Java provides a no-
argument constructor, called the default constructor.

交通大學資訊工程學系 蔡文能 第 69頁


Java OOP-class

The Life Cycle of an Object -- Access


Using Objects
 Referencing an Object's Variables
objectReference.variable
Example:
int areaOfRectangle = rect.height * rect.width;
 Calling an Object's Methods
objectReference.methodName(); or
objectReference.methodName(argumentList);
Example:
rect.move(15, 37);
int areaOfRectangle =
new Rectangle(100, 50).area();

交通大學資訊工程學系 蔡文能 第 70頁


Java OOP-class

The Life Cycle of an Object – Cleanup


Cleaning Up Unused Objects
 An object is eligible for garbage collection when there are no more
references to that object.
 The Garbage Collector
Automatically frees an object, if not referenced.
prevents memory leaks
claimed delay ~200ms for 4MB
Mark-sweep garbage collector
The garbage collector runs in a low-priority thread.
 When the system runs out of memory.
 In response to a request from a Java program.
 When the system is idle.

交通大學資訊工程學系 蔡文能 第 71頁


Java OOP-class

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

Example for Overriding (1/2)


class Point {
protected int x,y;
Point(int x, int y) {this.x = x; this.y = y;}
void draw(){
System.out.println(“Point at”+x+”,”+y);
};
}
Subclassing:
class Cpoint extends Point{
private Color c;
Cpoint(int i, int j, Color c){
super(i,j);
this.c =c;
};
void draw(){
System.out.println(“Color Point at ” + i + ”,” + j + ”,” + c);
};
}

交通大學資訊工程學系 蔡文能 第 73頁


Java OOP-class

Example for Overriding (2/2)


class PointApp{
public static void main(){
Point p = new Point(5,5);
Cpoint cp = new Cpoint(1,1,Red);
p.draw();
cp.draw();
p = cp;
p.draw();
// call Point’s draw() or Cpoint’s draw()?
}
}

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) { . . . }
}

 Overloaded methods are differentiated by the number and type of the


arguments.
 A subclass may override a method in its superclass.
The overriding method must have the same name, return type, and parameter
list as the method it overrides.

Java 不可以 operator overloading

交通大學資訊工程學系 蔡文能 第 75頁


Java OOP-class

Abstract Classes in Java


• Abstract classes created using the abstract keyword:
public abstract class MotorVehicle { … }
• In an abstract class, several abstract methods are declared.
- An abstract method is not implemented in the class, only declared. The
body of the method is then implemented in subclass.
- An abstract method is decorated with an extra “abstract” keyword.
• Abstract classes can not be instantiated! So the following is
illegal:
MotorVehicle m = new MotorVehicle; // 錯 !
// 抽象類別不能拿來生出物件
// 因為抽象的東西根本不存在
交通大學資訊工程學系 蔡文能 第 76頁
Java OOP-class

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

Example of Abstract Classes (1/2)


Example:
abstract class Stack {
abstract void push(Object o);
abstract Object pop();
}

public class ArrayStack extends Stack {


.... // declare elems[] and top;
void push(Object o) { elems[top++] = o; }
Object pop() { return elems[--top]; }
}

class LinkedStack extends Stack {


.... // declare ...
void push(Object o) { .... }
Object pop() { .... }
}

交通大學資訊工程學系 蔡文能 第 78頁


Java OOP-class

Example of Abstract Classes (2/2)

// ============================== Another file


...
static public int testStack(Stack s) { ....
s.push(x); s.push(y);
o1 = s.pop(); o2 = s.pop();
// check if o1 == y && o2 == x.
}
...
ArrayStack as = new ArrayStack();
testStack(as);
...

交通大學資訊工程學系 蔡文能 第 79頁


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.

• Interface can be added to a class that is already a subclass of


another class. (implements)
• To declare an interface:
public interface ImportTax {
public double calculateTax( );
}
交通大學資訊工程學系 蔡文能 第 80頁
Java OOP-class

Example of Interfaces (1/2)


interface Stack {
void push(Object o);
Object pop();
}

public class ArrayStack implements Stack {


.... // declare elems[] and top;
void push(Object o) { elems[top++] = o; }
Object pop() { return elems[--top]; }
}

class LinkedStack implements Stack {


.... // declare ...
void push(Object o) { .... }
Object pop() { .... }
}

交通大學資訊工程學系 蔡文能 第 81頁


Java OOP-class

Example of Interfaces (2/2)

//============================== Another file


...
static public int testStack(Stack s) { ....
s.push(x); s.push(y);
o1 = s.pop(); o2 = s.pop();
// check if o1 == y && o2 == x.
}
...
ArrayStack as = new ArrayStack();
testStack(as);
...

交通大學資訊工程學系 蔡文能 第 82頁


Java OOP-class

Difference between Abstract Class and Interface

• An abstract class is a class containing several abstract


methods.
Each abstract method is prefixed with the keyword “abstract”.
• An abstract class can not be instantiated but can be extended
(subclassed).
• An interface contains only abstract methods and constants.
Each abstract method is not prefixed with the keyword
“abstract”.
• An interface can only be implemented.

交通大學資訊工程學系 蔡文能 第 83頁


Java OOP-class

How C++ Deals with Interfaces


or Abstract Classes
Use virtual functions:
class Stack {
virtual void push(void* o) = NULL;
virtual void* pop() = NULL; // NULL 就是 0
}
// 注意 C++ 只有 virtual 函數才可寫 = NULL; 或 = 0;
// 寫 = NULL; 或 =0; 的 virtual function 叫做 pure virtual
function
// Java 則永遠自動 virtual
What are the internal designs?
 Key for the designs of COM/DCOM (MicroSoft)

交通大學資訊工程學系 蔡文能 第 84頁


Java OOP-class

Example for C++


class ArrayStack : Stack {
.... // declare elems[] and top;
void push(Object o) { elems[top++] = o; }
Object pop() { return elems[--top]; }
}
class LinkedStack : Stack {
.... // declare ...
void push(Object o) { .... }
Object pop() { .... }
}
============================== Another file
...
int testStack(Stack s) { ....
s.push(x); s.push(y);
o1 = s.pop(); o2 = s.pop();
// check if o1 == y && o2 == x.
}
...
ArrayStack as = new ArrayStack();
testStack(as);
...

交通大學資訊工程學系 蔡文能 第 85頁


Java OOP-class

Packages and Library


Organize class name space
Hierarchical division must be reflected in directory structure, i.e.,
package cyc.sys;
import java.io.*;
class Login { /* in fact, this is cyc.sys.Login */ }
Default packages (library) -- JDK
 java.lang - Object, Thread, Exception, String,...
 java.io - InputStream, OutputStream, ...
 java.net - Networking
support for Socket & URL-based objects
 java.awt - Abstract window toolkit
defines a simple, restricted windowing API
 java.util - Hashtable, Vector, BitSet, Regexp, ..
 java.tools - Compilation, Debugging, Documentation
 …

交通大學資訊工程學系 蔡文能 第 86頁


Java OOP-class

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

Java 並沒有 graphics.Rectangle

交通大學資訊工程學系 蔡文能 第 87頁


Java OOP-class

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++)

static: only one copy for all instances


abstract: left unimplemented
final: not overridden
native: methods implemented in native code.
synchronized: described in Thread
transient: data that is not persistent

交通大學資訊工程學系 蔡文能 第 88頁


Java OOP-class

Comparisons

Controlling Access to Members of a Class

Specifier Class Subclass Package World


private X
protected X X X
public X X X X
package X X

注意西方人是打 X 表示勾選 !

交通大學資訊工程學系 蔡文能 第 89頁


Java OOP-class

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
}
}

交通大學資訊工程學系 蔡文能 第 90頁


Java OOP-class

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;

Final methods: methods that cannot be overridden.


 Prevent clients from overriding.
 Allow for JIT to optimize.

交通大學資訊工程學系 蔡文能 第 91頁


Java OOP-class

Transient vs. Volatile


transient : used in object serialization to mark
member variables that should not be serialized.
volatile : used to prevent the compiler from
performing certain optimizations on a member.

交通大學資訊工程學系 蔡文能 第 92頁


Java OOP-class

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.

交通大學資訊工程學系 蔡文能 第 93頁


Java OOP-class

Types of Nested Class


class EnclosingClass{
. . .
static class AStaticNestedClass {
. . .
}
class InnerClass {
. . . /* static is wrong in this inner class */
}
}
A static nested class is called: a static nested class.
 A static nested class cannot refer directly to instance variables or
methods defined in its enclosing class
A nonstatic nested class is called an inner class.
 An inner class is associated with an instance of its enclosing class and
has direct access to that object's instance variables and methods.
 Because an inner class is associated with an instance, it cannot define
any static members itself.

交通大學資訊工程學系 蔡文能 第 94頁


Java OOP-class

Nested vs. Inner


To help differentiate the terms nested class and inner class:
 The term "nested class" reflects the syntactic relationship between
two classes.
 In contrast, the term "inner class" reflects the relationship between
instances of the two classes.
An instance of InnerClass can exist only within an instance of
EnclosingClass,
It has direct access to instance variables and methods of its enclosing
instance.
class EnclosingClass {
. . .
class InnerClass {
. . .
}
}

交通大學資訊工程學系 蔡文能 第 95頁


Java OOP-class

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;

// ... code for Stack's methods and constructors not shown...

public Enumeration enumerator() {


return new StackEnum();
}

class StackEnum implements 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--);
}
}
}

交通大學資訊工程學系 蔡文能 第 96頁


Java OOP-class

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--);
}
};
}
}

交通大學資訊工程學系 蔡文能 第 97頁


Java OOP-class

Upcasting and Polymorphism(1/4)


• Upcasting: Taking an object reference and treating it as a
reference to its base type is called upcasting, because of the
way inheritance trees are drawn with the base class at the top.

交通大學資訊工程學系 蔡文能 第 98頁


Java OOP-class

Upcasting and Polymorphism (2/4)


• Polymorphism: In Java, the principle that the actual type of the
object determines the method to be called is called polymorphism.
class Shape { Shape
void draw( ) {} draw()
void erase( ) {} erase()

}
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

Upcasting and Polymorphism (3/4)


class Square extends Shape {
void draw( ) {
System.out.println("Square.draw( ) ");
}
void erase( ) {System.out.println("Square.erase( )");}}

class Triangle extends Shape {


void draw( ) {
System.out.println("Triangle.draw( )");
}
void erase( ) {System.out.println("Triangle.erase( )");}
}

交通大學資訊工程學系 蔡文能 第 100頁


Java OOP-class

Upcasting and Polymorphism (4/4)


public class Shapes {
public static Shape randShape() {
switch((int) (Math.random()*3)) {
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
default : return new Circle();}
}
public static void main(String[] args) {
Shape[] s = new Shape[9];
for (int i = 0; i < s.length; i++)
s[i] = randShape();
//Make polymorphism method calls:
for (int i = 0; i < s.length; i++) s[i].draw();
}
}
交通大學資訊工程學系 蔡文能 第 101頁
Java OOP-class

Polymorphism in C++ (1/2)


// polymo.cpp -- CopyWrong by [email protected]
#include <iostream.h>
class Shape{
public:
virtual // 把這列去掉再 run 看看
void draw( ) { cout << "drawing\n"; }
};
class Line: public Shape{
public:
void draw( ) { cout << "draw a line\n"; }
};
class Circle: public Shape{
public:
void draw( ) { cout << "here is a circle\n"; }
};

交通大學資訊工程學系 蔡文能 第 102頁


Java OOP-class

Polymorphism in C++ (2/2)


int main(){
Circle * ppp;
Shape * fig[9];
// ppp = new Shape(); // error
ppp = (Circle *)new Shape();
ppp -> draw();
ppp = (Circle *)new Line(); ppp -> draw();
ppp = new Circle(); ppp -> draw();
cout << "======" << endl;
fig[0] = new Line();
fig[1] = new Circle();
fig[2] = new Circle();
fig[3] = new Line(); fig[4] = new Circle();
for(int k=0; k<5; k++){
fig[k] -> draw();
}
}

交通大學資訊工程學系 蔡文能 第 103頁


Java OOP-class

Java: OOP, Object, Class

謝謝捧場
http://www.csie.nctu.edu.tw/~tsaiwn/course/java/
蔡文能
交通大學資訊工程學系 蔡文能 第 104頁

You might also like