sl-110 fundamental of java programming language 補充資料 sean cheng [email protected]

96
SL-110 Fundamental of Java Programming Language 補補補補 Sean Cheng [email protected]

Upload: reynold-fleming

Post on 27-Dec-2015

261 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

SL-110Fundamental of Java

Programming Language 補充資料

Sean Cheng

[email protected]

Page 2: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Sun Java Course Path

SL-110Java 初階程式設計

SL-275Java 程式設計

OO-226OOAD Using UML

SL-314Java Web 元件

FJ-310J2EE 相容應用程式

SL-351Java 進階商用元件

SL-285Java 程式實務

Page 3: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Explaining Java Technology

Module 1

Page 4: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

課程準備

• 課程環境設定– Download Java SDK 及文件– 安裝 Java SDK 及文件– 環境變數設定

Path = <JAVA_HOME>\bin ClassPath = .

– 安裝文字編輯器 (EditPlus2)

Page 5: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

跨平台

Java 虛擬機器

Java 程式

Java API

作 業 系 統

硬 體

Java 平台

• Java Platform– 只要電腦上有 java 平台,無論作業作業系統是 Wi

ndows 、 Mac OS 或 Linux , Java 程式都可以執行

– 某些情況下仍須少量修改• Java Runtime Environment (JRE)

– Java Virtual Machine(ByteCode 解譯器 )

– Java Class Libraries (API)

• 解譯式語言

Page 6: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

• Loads Code– Class Loader

• Verifies Code– Bytecode Verifier

• Executes Code– Runtime Interpreter

Java Runtime Environment

………………*.java *.class

javacClass Loader

Byte codeVerifier

JITCode

GeneratorRuntime

Hardware

java

Interpreter

………………

Page 7: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Java Technology Product Groups

HotSpot JVM KVM Card VM

Java Language

Java 2Enterprise

EditionJava 2

StandardEdition

Java 2 Micro Edition

Page 8: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

JRE vs. SDK

Page 9: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Module 2

Analyzing a Problem Using

Object-Oriented Analysis

Page 10: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

軟體開發三階段

• OOA : 物件導向分析• OOD : 物件導向設計• OOP : 物件導向程式開發

Page 11: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

物件導向分析

• Identify Problem Domain 辨識問題範圍• Identify Object 辨識物件• Recognized Object 確認物件• Identify Object’s Attribute & Operation

辨識物件之屬性及行為

Page 12: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Problem Statement

DirectClothing, Inc. sells shirts from their catalog. Business is growing 30 percent per year, and they need a new order entry system. You have been contracted by DirectClothing to design the new system.

DirectClothing produces a catalog of clothing every six months and mails it to subscribers. Each shirt in the catalog has an item identifier (ID), one or more colors (each with a different color code), one or more sizes, a description, and a price.

DirectClothing accepts checks and all major credit cards.

To place an order, customers can call DirectClothing to order directly from a customer service representative (CSR), or customers can mail or fax an order form to DirectClothing.

Page 13: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Problem Statement - continue

Orders that are mailed or faxed are entered by a CSR.

DirectClothing would like to give the customer the option of entering an order online through the Internet. The items available online are priced according to the current catalog.

As the order is entered in the system, each item’s availability (quantity-on-hand) is verified. If one or more items are not currently available (in DirectClothing’s warehouse), then the order is placed on hold until the items arrive at the warehouse. After all of the items are available, payment is verified and the order is submitted to the warehouse for assembly and for shipping to the customer’s address.

If the order is received by phone, the CSR gives the customer an order ID, which is used to track the order throughout the process. The CSR also gives the CSR’s telephone extension to the customer.

Page 14: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Identifying Objects

DirectClothing, Inc. sells shirts from their catalog. Business is growing 30 percent per year, and they need a new order entry system. You have been contracted by DirectClothing to design the new system.

DirectClothing produces a catalog of clothing every six months and mails it to subscribers. Each shirt in the catalog has an item identifier (ID), one or more colors (each with a different color code), one or more sizes, a description, and a price.

DirectClothing accepts checks and all major credit cards.

To place an order, customers can call DirectClothing to order directly from a customer service representative (CSR), or customers can mail or fax an order from to DirectClothing.

Page 15: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Identifying Objects - continue

Orders that are mailed or faxed are entered by a CSR.

DirectClothing would like to give the customer the option of entering an order online through the Internet. The items available online are priced according to the current catalog.

As the order is entered in the system, each item’s availability (quantity-on-hand) is verified. If one or more items are not currently available (in DirectClothing’s warehouse), then the order is placed on hold until the items arrive at the warehouse. After all of the items are available, payment is verified and the order is submitted to the warehouse for assembly and for shipping to the customer’s address.

If the order is received by phone, the CSR gives the customer an order ID, which is used to track the order throughout the process. The CSR also gives the CSR’s telephone extension to the customer.

Page 16: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

辨識物件的原則

• 物件通常為名詞– Account, Shirt

• 物件屬性通常也為名詞– color, size

• 物件的行為通常為動詞或名詞與動詞的組合– display, submit order

Page 17: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

物件導向設計

• Design Class– 為物件設計類別 ( 藍圖 )

• Modeling Class– 視覺化所設計的類別

Page 18: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

類別 vs. 物件

• 物件是類別的一個實體 • 類別是同類型物件的共同藍圖• Java programmer 設計類別及類別之間

的互動關係 .• Java 應用程式執行時 ,JVM 根據類別定

義建立物件 ( 系統中配置記憶體 ), 並處理物件之間互動產生之的狀態變化 ( 記憶體中的儲存值的改變 )

Page 19: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Developing and Testing a Java Technology Program

Module 3

Page 20: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

物件導向程式運作• 物件可分為

– 單獨可執行的物件– 附屬於其他系統動作的物件

• Java 應用程式執行– 一個 main Object( 包含起始方法作為程式的

起始點 )– main 物件建立所需之其他物件– 利用物件之間的互動來完成工作

Page 21: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Class Structure

• Class 基本結構– Class declaration– Attributes– Methods (operations)– Comments

Optional

Page 22: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Structuring Classes

public class Shirt {

public int shirtID = 0; public String description = "-description required-"; public char colorCode = 'U'; public double price = 0.0; public int quantityInStock = 0; public void displayShirtInformation() { System.out.println("Shirt ID: " + shirtID); System.out.println("Shirt description:" + description); System.out.println("Color Code: " + colorCode); System.out.println("Shirt price: " + price); System.out.println("Quantity in stock: " + quantityInStock); }}

Shirt

shirtID : int

description : String

colorCode : char

price : double

quantityInStock : int

displayShirtInformation()

Page 23: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Class Declaration

[modifiers] class <class_name> {

}• Modifier 為 public 的類別 , 需存在 class_name.java

的檔案中• 一個 Java 檔案 , 可包含一個以上的類別宣告• 多個類別宣告在一個 Java 檔案中 , 只能有一個 public

的類別

Accessibility

KeywordName of the class

Page 24: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Attribute Variable Declaration

AccessibilityPrimitive or reference type

Name of the attributeInitialize literal values

[modifiers] <type> <name> [=initial_values];

• 程式中用變數來存放需使用到的資料• 變數定義在 class body 內用來表示物件的屬性• 變數也可以用存放臨時使用到的資料

Page 25: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Method Declaration

AccessibilityReturn data type

Name of the methodArguments list

[modifiers] <return_type> <name> ([arguments]) {

}• 方法如不需傳回值 ,return type 為 void

• Argument list:

– 可為 0~N 個– Type Name

– 若有一個以上 , 用,隔開

Page 26: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Comments

• 單行註解public int shirtID = 0; //Default ID for the shirt

// The color codes are R= Red, B= Blue

• 多行註解/*

this is a multi-line comment

*/

• JavaDoc 註解/**

The following comment will be show in JavaDoc

*/

Page 27: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

main Method

public static void main (String args[]) {

}• 符合標準的 main(), 才可被 JRE 當作程式的進入點• Modifier

– 可加上 final– 順序可不同

• 字串陣列可用另一方法表示– String [] args

• 字串陣列名稱不一定要為 args

ModifiersNo return data

Name of the methodString array argument

Page 28: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Compiling & Executing a Java Program

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); }}

HelloWorld.java

………………

HelloWorld.class

javac java

Page 29: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Module 4

Declaring, Initializing and Using Variables

Page 30: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Attribute vs. Local Variable • Attribute

– Variable 宣告在 class 定義內 ,method 區塊之外– 也稱為 member variable, instance variable– 當物件實體化後 , 每一物件即各自擁有自己的變數資

料 , 互不影響– 如未定義初始值 , 會有 default 值 (int i; 此時 i=0)– 隨物件存放在 Heap 記憶體中

• Local variable– Variable 宣告 method 區塊之內– 區域變數只在宣告的區段 {} 中有效– 宣告時不使用 modifier(final 例外 )– 必須自訂初始值– 存放在 Stack 記憶體中

Page 31: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Literals

• A value: 出現在程式中的一個數值• boolean

– 只有 true 和 false

• 整數– 三種型式 : 十 , 八 , 十六進位– 兩種型態 : int ( 預設 ) 與 long ( 字尾加上 L)

• 浮點數– 兩種型態 : float ( 字尾加上 F) 與 double ( 預設 , 字

尾加上 D)

• 字元 : 使用單引號 (‘)• 字串 : 使用雙引號 (“)

Page 32: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

2‘s complement

• 2 的補數表示法– 已有某數 X 的 2 進位表示法 , 尋找 -X 之 2 進

位表示法1. 將所有 10, 01

2. 將 Step1 結果 +1

+5 00000110 11010100 -x

11111001 00101011

+ 1 + 1

-5 11111010 00101100 +x = 44

= -44

Page 33: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Escape Character

\b \u0008 Back Space

\t \u0009 Tab

\n \u000a New Line

\f \u000c Form feed

\” \u0022 “

\’ \u0027 ‘

\\ \u005c \

\r \u000d Return

Page 34: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Primitive Data Types

Type Length Range Literal examples Init. Value

boolean 1 true, false true, false false

byte 8 -27~27-1 2, -114 0

short 16 -215~215-1 2, -32699 0

int 32 -231~231-1 2, -147344778 0

long 64 -263~263-1 2, -2036854708L 0L

float 32 IEEE754 99F, -32699.01F 0.0F

double 64 IEEE754 -111, 21E12 0.0

char 16 0~65535 ‘A’, ‘x’, ‘3’, ‘ 中’ , ‘\n’, ‘\u0063’

‘\u0000’

Page 35: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Identifier

• 下列四種字元組成– Unicode letters A-Z, a-z, 中文 , …– Underscore _– Dollar sign $, ¥, £…– Digits 0,1,…9 ( 不能出現在起始字元 )

• 不可為 keywords / Reserved words

• 大小寫有別 Case sensitive

Page 36: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Key words & Reserved Word

Keywords abstract assert boolean break byte case catch char class continue default do double else extends final finally float for if implements import instanceof int interface long native new package private protected public return short static strictpf super switch synchronized this throw throws transient try void volatile while

Reserved words false null true const goto

Page 37: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Promotion

Promotion 發生時間

– 1. 指定運算– 2. 算數運算– 3.方法呼叫

byte short int long float double

char boolean

Page 38: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Module 5

Creating and Using Objects

Page 39: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Declarationpublic class Shirt { public int shirtID = 0; public String description = "-required-"; public char colorCode = 'U'; public double price = 0.0; public void displayShirtInformation() { System.out.println("Shirt ID: " + shirtID); System.out.println("Shirt description:" + description); System.out.println("Color Code: " + colorCode); System.out.println("Shirt price: " + price); }}

Shirt myShirt;

myShirt = new Shirt();

myShirt

Stack memory

Page 40: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Instantiatingpublic class Shirt { public int shirtID = 0; public String description = "-required-"; public char colorCode = 'U'; public double price = 0.0; public void displayShirtInformation() { System.out.println("Shirt ID: " + shirtID); System.out.println("Shirt description:" + description); System.out.println("Color Code: " + colorCode); System.out.println("Shirt price: " + price); }}

Shirt myShirt;;

myShirt = new Shirt();

0

“-required-”

‘U’

0.0

shirtID

description

colorCode

pricemyShirt

Stack Memory Heap Memory

Page 41: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Initializingpublic class Shirt { public int shirtID = 0; public String description = "-required-"; public char colorCode = 'U'; public double price = 0.0; public void displayShirtInformation() { System.out.println("Shirt ID: " + shirtID); System.out.println("Shirt description:" + description); System.out.println("Color Code: " + colorCode); System.out.println("Shirt price: " + price); }}

Shirt myShirt;;

myShirt = new Shirt();

0

“-required-”

‘U’

0.0

shirtID

description

colorCode

price0x01234567myShirt

Stack Memory Heap Memory

Page 42: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

7

0x01234567

0x07654321

x

myShirt

yourShirt

int x = 7;Shirt myShirt = new Shirt(); yourShirt = new Shirt();

0

“-required-”

‘U’

0.0

shirtID

description

colorCode

price

0

“-required-”

‘U’

0.0

shirtID

description

colorCode

price

Stack Memory Heap Memory

Page 43: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

7

0x01234567

0x07654321

x

myShirt

yourShirt

Shirt myShirt = new Shirt(); yourShirt = new Shirt();myShirt.colorCode = ‘R’;yourShirt.colorCode = ‘G’;

0

“-required-”

‘R’

0.0

shirtID

description

colorCode

price

0

“-required-”

‘G’

0.0

shirtID

description

colorCode

price

Stack Memory Heap Memory

Manipulate Data

Page 44: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

System.out.println(myShirt.colorCode);myShirt.displayShirtInformation()

Accessing Data

0

“-required-”

‘R’

0.0

shirtID

description

colorCode

price0x01234567myShirt

Stack Memory Heap Memory

Page 45: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

String Literal Pool

• JVM 中存放字串的共用區域• 以 String identifier = string_literal; 方式

宣告的字串物件儲存到 string pool 中• 新增字串物件到 String pool 前會先檢查是否有相同樣的物件 , 如果有的話直接傳回參考值 , 不會新增字串物件

Page 46: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

String literal Pool

public class StringPoolTest { public static void main(String[] args) {

String s1 = "Hello";String s2 = "Hello";String s3 = new String("Hello");String s4 = new String("Hello");

System.out.println("s1==s2 is " + (s1==s2));System.out.println("s3==s4 is " + (s3==s4));

}}

Hello

Hello

Hello

Literal Pool

true

false

Page 47: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Module 6

Using Operators and Decision Constructs

Page 48: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

比較運算

運算子 運算元 Sample

== 布林 , 數字 ,字元 , 物件

true != flase

String s = “Hello”;

s == “Hello”!=

>=

數字 , 字元>

<

<=

instanceof 物件 , 類別 S instanceof String

Page 49: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

基本邏輯運算

AND true false

true true false

false false false

XOR true false

true false true

false true false

NOT

true false

false true

OR true false

true true true

false true false

Page 50: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

邏輯運算• 一般邏輯運算子

&, | , ! , ^

• 捷徑邏輯運算子 (shirt-circuit)& &, | |

– 捷徑 : 當左式已經足以判斷整個運算的結果時 ,右式就不必做了 , 若左式不足以判斷整個運算的結果時 ,右式仍然要做

– 邏輯判斷會改變變數的值時 ,易產生非預期的結果

&& X

true X

false false

|| X

true true

false X

Page 51: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Branching Statements – if/else

if (boolean) { statements;}

if (boolean) { statements;} else { statements;}

條件判斷

if 程式碼

truefalse

else 程式碼

條件判斷

if 程式碼

true

false

Page 52: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Branching Statements – else if

if (boolean) { statements;} else if (boolean) { statements;} else { statements;}

else if 程式碼

true

false

else 程式碼

條件判斷 if 程式碼true

false

條件判斷

Page 53: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Branching Statements - switch

switch (variable) {case literal_value:

statements;[break;]

case literal_value:statements;[break;]

[default:]statements;

}

Page 54: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Case判斷 程式碼true

false

default 程式碼

Case判斷 程式碼true

Switch 條件

false

Case判斷 程式碼

default 程式碼

false

true

Case判斷 程式碼true

Switch 條件

false

Page 55: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Module 7

Using Loop Constructs

Page 56: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

while Loop

while (boolean) {statements;

}迴圈結束條件判斷

程式碼

true

false

Page 57: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

do/while Loop

do {

statements;

} while (boolean); 迴圈結束條件判斷

程式碼

true

false

Page 58: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

for Loop

for ([initialize[,initialize…]]; [boolean_expression]; [update[,update…]]) {statements;

}

for迴圈執行時 :• 變數宣告 . 只執行一次• 布林判斷式 . 每次迴圈開始之前• 更新狀態 . 執行 code_blocks 之後 , 2 之前

1 2 3

Page 59: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

迴圈結束條件判斷

程式碼

true

false

改變控制迴圈變數數值

控制迴圈初始值設定

Page 60: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Module 8

Developing and Using Methods

Page 61: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Method Declaration

[modifiers] <return_type> <name> ([arguments]) {

}

Accessibility

Return data type

Name of the method

Arguments list

Page 62: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Call Stack mechanism

public class ShirtTest { …… public static void main (String args[]) { Shirt myShirt = new Shirt(); myShirt.display(); ……… } }

public class Shirt {…… public void display() { System.out.println(shirtID); ……… } }

public class PrintStream { …… public void .println(int i){ …………… } }

Page 63: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

static attribute

public class Count { public int no; public static int counter = 0;

public void print(){ System.out.print(“counter = “ + counter); System.out.print(“no = “ + no); }}

public class CountTest { public static void main(String [] args) { Count c1 = new Count(); Count c2 = new Count(); c1.no = 1; c2.no = 2; c1.counter = 2; c1.print(); c2 = print(); }}

2

Count

no

c2

2

Count

counter

1

Count

no

c1

Page 64: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

static attribute

• 用來表示全域變數 (Global Variable)

• 可用兩種方法存取– ClassName.attributeName;– objectName.attributeName;

Page 65: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

static method

• 用途– 提供 utility 方法– 存取 static variable

• 語法[modifiers] static return_type name([args_list]) { }

Page 66: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

static method• 用法

– ClassName.methodName();– objectName.methodName();

• 規則– static methods 內不可以使用 instance member

Instance variable Instance method

– 只能用 local variables (parameter) static variables 其他 static method

Page 67: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Overloaded Method

public class Calculator { public int sum(int numberOne, int numberTwo){ System.out.println("Method One"); return numberOne + numberTwo; }

public float sum(float numberOne, float numberTwo) { System.out.println("Method Two"); return numberOne + numberTwo; }

public float sum(int numberOne, float numberTwo) { System.out.println("Method Three"); return numberOne + numberTwo; }}

public class CalculatorTest {

public static void main(String [] args) { Calculator myCalculator = new Calculator(); int totalOne = myCalculator.sum(2,3); System.out.println(totalOne);

float totalTwo = myCalculator.sum(15.99F, 12.85F); System.out.println(totalTwo);

float totalThree = myCalculator.sum(2, 12.85F); System.out.println(totalThree); }}

Page 68: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Module 9

Implementing Encapsulation and Constructors

Page 69: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

• 封裝 encapsulation– 保護類別中的資料 , 不讓資料被誤用或破壞– 隱藏實作的細節

• 封裝的方法1. 更改屬性的修飾子2. 提供存取屬性的方法

Getter & Setter Setter提供保護資料的邏輯

3. 欲存取此類別之資料 , 需使用類別所提供的方法來存取

Encapsulation

身份確認 存款

提款 餘額查詢

帳號戶名餘額

行為( 方法 )

狀態( 屬性 )

Page 70: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

public class People { public String name = “default”; public int age = 0;}

public class People { private String name = “default”; private int age = 0;

public void setName(String newName) { name = newName; }

public String getName() { return name; }

public void setAge(int newAge) { age = newAge; }

public int getAge() { return age; }}

Encapsulation - continue

Page 71: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Encapsulation - continue

public class People { private String name = “default”; private int age = 0;

public void setName(String newName) { name = newName; }

public String getName() { return name; }

public void setAge(int newAge) { if(newAge > 0) age = newAge; }

public int getAge() { return age; }}

setter methodsetXXX( )

getter methodgetXXX( )

Page 72: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Encapsulation - continue

public class People { private String name = “default”; private int age = 0;

public void setName(String newName) { name = newName; }

public String getName() { return name; }

public void setAge(int newAge) { if(newAge > 0) age = newAge; }

public int getAge() { return age; }}

public class PeopleTest { public static void main(String args[]) { People p = new People();

p.name = “John”; p.age = 30;

p.setName(“John”); p.setAge(30); System.out.println(“Name: “ + p.getName()); System.out.println(“Age: “ + p.getAge()); }}

compile error!

Page 73: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Creating Constructors

[modifiers] class <class_name> {

[modifiers] constructor_name([arguments]) {

code_blocks

}

}

Accessibility

Same as class_name

Arguments list

Page 74: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Constructors

• 與類別名稱一樣• 沒有回傳型態• 自行建立後預設建構子即失效• 可以多載 (Overloading)

Page 75: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Default Constructor

public class People { private String name; private int age; public String show () { System.out.println(name + “ “ + age); }}

public class People { private String name; private int age; public People() {} public String show () { System.out.println(name + “ “ + age); }}

javac People.java

Page 76: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Constructors overloading

public class People { private String name; private int age;

public People(String newName) { name = newName; age = 0; } public People(String newName, int newAge) { name = newName; age = newAge; }}

Page 77: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Module 10

Creating and Using Arrays

Page 78: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

type [ ] array_identifier;

type array_identifier [ ];Ex:

int [] age;

Shirt shirts[];

Declaration

x

age

shirts

Stack Memory

Page 79: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Instantiation

array_identifier = new type[length];Ex:

age = new int [4];

shirts = new Shirt [3];

7

0x01234567

0x02345678

x

Age

Shirts

0

0

0

0

Stack Memory Heap Memory

Page 80: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Initialization

array_identifier [index] = value;Ex:

age [2] = 3;

shirts [0] = new Shirt();

7

0x01234567

0x02345678

x

age

shirts

0

1

3

0

Stack MemoryHeap Memory

0x03456789

0

“-required-”

‘U’

0.0

shirtID

description

colorCode

price

Page 81: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Declaration, Instantiation & Initialization

宣宣告告

實實體體化化

初初始始化化

int[] i;

i = new int[3];

i[0] = 1;i[1] = 3;i[2] = 5;

int[] i = new int[3];

i[0] = 1;i[1] = 3;i[2] = 5;

int[] i = {1, 3, 5};

Page 82: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Two-Dimension Array

Quarter1 Quarter2 Quarter3 Quarter4

Year1

Year2

Year3

Year4

Year5

Page 83: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

type [ ][ ] array_identifier;

type array_identifier [ ][ ];Ex:

int [][] yearlySales;

Declaration

x

yearlySales

Stack Memory

Page 84: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Instantiation

array_identifier = new type [number_of_arrays][length];

Ex:

yearlySales = new int [3][4];

7

0x01234567

x

yearlySalese

0x12345678

0x23456789

0x34567890

Stack Memory

Heap Memory

0

0

0

00

0

0

00

0

0

0

Page 85: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Initialization

array_identifier [number_of_arrays] [index] = value;

Ex:

yearlySales [1][2] = 500;

7

0x01234567

x

yearlySalese

0x12345678

0x23456789

0x34567890

Stack Memory

Heap Memory

0

0

0

00

0

500

00

0

0

0

Page 86: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Module 11

Implementing Inheritance

Page 87: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Inheritance

• 繼承– 類別與類別之間 , 存在一般化 (Generalize), 或特殊化 (specialize) 的關係

– “is A” relationship– 子類別可被視為父類別來看待– 子類別 (sub-class)繼承父類別 (super-class) 的

所有特徵

Page 88: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

SubClass declaration

[modifiers] class <class_name> [extends] [class_name] {

}Accessibility

Keyword

Keyword

Name of the super class

Name of the class

Page 89: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Abstraction

• 抽象化– 從物件中抽出或排除其細節部份 ,歸納其最重要的特徵

– 調整看待事物的角度 ,思考事物的分類抽象化的類別通常無法被充分定義 A Manager is an Employee

A Engineer is an Employee提供未來擴充的彈性

Page 90: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

Employee, Manager, Engineer

public class Employee { private String name; private int salary ;

public void show () { System.out.println(name); System.out.println(salary); }}

public class Manager { private String name; private int salary; private String department;

public void show () { System.out.println(name); System.out.println(salary); System.out.println(department); }}

Page 91: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

public class Engineer { private String name; private int salary ; private String[] skill ;

public void show () { System.out.println(name); System.out.println(salary); for(int i=0; i < skill.length; i++) System.out.println(skill[i]); }}

public class Employee { private String name; private int salary ;

public void show () { System.out.println(name); System.out.println(salary); }}

Page 92: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

public class Manager extends Employee{ private String department; public void show () { System.out.println(name); System.out.println(salary); System.out.println(department); }}

public class Employee { private String name; private int salary ;

public void show () { System.out.println(name); System.out.println(salary); }}

public class Engineer extends Employee{ private String[] skill ; public void show () { System.out.println(name); System.out.println(salary); for(int i=0; i < skill.length; i++) System.out.println(skill[i]); }}

Page 93: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

套件 (package) 的使用

• 目的– 將許多不同的類別檔案實際分門別類放在

一起– 使類別名稱不相衝突– 提供 package(default) 的存取保護

Page 94: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

使用 Package 成員

• Package 下類別使用– 引用同 package 之下的類別 , 可直接使用類

別短名– 引用不同 package 之下的類別 , 不可直接使

用類別短名 , 需使用類別長名• 類別的長名 vs.短名

– 短名 : 類別名稱本身外– 長名 :短名前面再加上其 package 名稱

Page 95: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

使用其他 Package 成員

• 使用其他 Package 成員– 以類別的長名存取– 引入 (import)package特定成員– 引入 (import) 成員所屬 package

Page 96: SL-110 Fundamental of Java Programming Language 補充資料 Sean Cheng sean.cheng@ever.com.tw

import 注意事項

• 預設自動 import– java.lang.*– default package(目前工作目錄 )

• 避免名稱混淆– 同一個短名 , 在 classapth 中可找到兩個不同

的長名定義時 , 仍需用類別長名來存取