Lec07 :: Object-Oriented Programmingsiam2dev.net/E_Learning/OOP/Lec07_Java_OOP_Class... · Agenda...

Preview:

Citation preview

11/01/61Page 1

Lec07 :: Object-Oriented Programming

โดย อ. นฐพงศ สงเนยมhttp://www.siam2dev.comxnattapong@hotmail.com

Last Update 12-01-2561

Class , Enum , Package , Interface , Inheritance , Generics , Inner Class

Agenda

• Object Oriented Programming Topic– PART I : Java Syntax [ Lec01 – Lec05,

Lec06]– PART II : Java OOP [ Lec07 …]

11/01/61Page 2

Agenda (cont.)• Unified Process• Class diagram• Class

– Attributes– Method

• Empty Class• Constructor• Overloading Constructor Method• Modifier

– Public– Private– Protected– Default

11/01/61Page 3

• SDLC : Software Development Life Cycle– วฏจกรในการพฒนาระบบแบบดงเดม

• 7 ขนตอน– 1. วเคราะหปญหา– 2. ออกแบบปญหา– 3. พฒนาโปรแกรม– 4. ทดสอบ– 5. ตดตงใชงาน– 6. บารงรกษา– 7. ทาเอกสารประกอบ

• Unified Process– กรรมวธทใชสาหรบการพฒนาระบบเชงวตถ

11/01/61Page 4

Unified Process โครงสรางกรรมวธ - Lifecycle Phases

เตรยมงาน (Inception) – นยามขอบเขตของโครงการ , ขอบเขตของระบบทจะพฒนา

OOAD : Object-Oriented Analysis and Design5

Inception Elaboration Construction Transition

time

Unified process แบงการพฒนาออกเปน 4 เฟส (phases)

ทารายละเอยด (Elaboration) – วางแผนโครงการ จดทารายละเอยดความตองการ จดสรางสถาปตยกรรมระบบ

จดสราง (Construction) – สรางและทดสอบโปรแกรม

ถายโอน (Transition) – ตดตงถายโอนระบบใหกบผใช

5

OOP

OOAD

Presenter
Presentation Notes
ในชวง Inception จะเปนการกำหนดขอบเขตของโครงการ ระบวาสงใดทอยในโครงการ สงใดไมอยในโครงการ การกำหนดขอบเขตทำไดโดยการระบถง actors ซงกคอผใชระบบ ระบถงสงทระบบตองกระทำ ทเรยกวา use cases ตามทผใชแตละกลมคาดหวง , we define the scope of the project, what is included, and what is not. We do this by identifying all the actors and use cases, and by drafting the most essential use cases (usually approximately 20 percent of the complete model). A business plan is developed to determine whether resources should be committed to the project. During Elaboration, we focus on two things: getting a good grasp of the requirements (80 percent complete), and establishing an architectural baseline. If we have a good grasp of the requirements and the architecture, we can eliminate a lot of the risks, and we will have a good idea what amount of work remains to be done. We can make detailed cost/resource estimations at the end of Elaboration. During Construction, we build the product in several iterations up to a beta release. During Transition, we transition the product to the end user and focus on end user training, installation, and support. The amount of time spent in each phase varies. For a very complex project with a lot of technical unknowns and unclear requirements, Elaboration may include three to five iterations. For a very simple project, where requirements are known and the architecture is simple, Elaboration may include only a single iteration.

UP

• สมมตไดรบงาน Project มา 1 Project UP คอจะแบง Project ออกเปนชวงเวลา 4 ชวงเวลา– Inception เตรยมงาน– Collaboration การลงรายละเอยด– Construction– Transition

11/01/61Page 6

12 เดอน

1-2 เดอน

1-2 เดอน

3-6 เดอน

1-2 เดอน

Abstractions

7

Classification

Generalization/Specialization

Association

Aggregation

Is member of

Is member of

Is member of

Is part of Is part of

Is part of

Is kind of Is kind of Is relate to Is relate to

Reviews OOAD concept

เราจะทาอยางไร จงจะไดคลาส ขน กอาศย กระบวนการเหลาน

หาคลาส และ หาวตถ และวตถ นนอยในคลาสใด

• เปนการทาความรจกคลาส และ ออบเจกต

• แลวออกมาเปนคลาส เปนออบเจกต

• จะไดคลาสพนฐานfundamental classes

11/01/61Page 8

Classification

Is member of

Is member of

Is member of

จงพฒนาระบบคลกนกรกษาโรคทวไป

• มคลาสอะไรบาง• ออบเจกตอะไรบาง

11/01/61Page 9

Class / Object คออะไร

ยา

เภสช

คนไข / ลกคา

ยาพารา

ยาแกอกเสบ

ยาดม

ยาหมอง

คลาส

Objects• Attribute คณสมบต/คณลกษณะทบงบอกถง

ความเปนวตถนน• Function คอ ความสามารถ พฤตกรรม สงวตถ

นนทาได หรอ หนาทของวตถ

11/01/61Page 10

นก

• Attribute– ปก– ปาก– ตา– ขา– ขน

• Function – บน– กน– เดน– รอง

11/01/61Page 11

• Attribute– ผม– ปาก– จมก– ตา– ...

• Function – นอน– กน– เดน– รอง

คนProblem Domain

• คลาส คอ กลมของวตถ

11/01/61Page 12

Abstractions

• จะไดคลาสและออบเจกตทงหมดทความสมพนธกน แลวสรางออกมาเปนแผนภาพออกมา เรยกวา classdiagram

• เมอไดแผนภาพคลาสมา กนามาสรางเปนซอฟตแวรตามแผนภาพคลาส

11/01/61Page 13

Class Diagram

• เปนโมเดลหนง ใน UML : Unified Modeling Language

• แผนภาพคลาส มาจากกระบวนการวเคราะหและออกแบบระบบเชงวตถ

• การปรบเปลยนจากเฟสออกแบบมาเปนเฟสการลงมอทาหรอพฒนาโปรแกรม (Transform from Designing phase to Implementation phase) จาเปนอาศยแผนภาพคลาสในการพฒนาโปรแกรม

11/01/61Page 14

11/01/61Page 15

OOP

• Class• Enum• Package• Interface• Inheritance• Generics• Inner Class

Class คออะไร

Objects คออะไร Class NameAttributeMethod

11/01/61Page 16

Class

•คลาส•สวนประกอบของคลาส•การสรางคลาส

11/01/61Page 17

คลาสในภาษาจาวา

• คลาสหรอแบบแปลนของวตถ จะถกเขยนอยในไฟลทมนามสกล java– เชน คลาสสเหลยมอาจจะถกเขยนอยในไฟลชอ

Rectangle.java

class ชอคลาส {

}

11/01/61Page 18

11/01/61Page 19

สวนประกอบของคลาส Class name

attributes

method

UML Class Diagram

11/01/61Page 20

Class name

+ attribute : Type

+ function() : Boolean- A() : Boolean# B() : boolean

Visibility- private+ public# protected

Class diagram

11/01/61Page 21

Class name

attributes

function

Class name

Data member

Method Member

OO java

11/01/61Page 22

สวนประกอบของคลาส

• เมธอด เปนสงทใชอธบายการทางานของวตถในคลาส – ชอเมธอดควรเปนคากรยา

• แอตทรบวท เปนสงทใชบอกถงลกษณะตางๆของวตถในคลาส

11/01/61Page 23

ตวอยางเมธอด

คลาส เมธอด/ฟงกชน/ความสามารถ/พฤตกรรม

นก กน(), บน(), สงเสยง()

โทรทศน เปด(), ปด(), เปลยนชอง(), ปรบเสยง()

สเหลยม คานวณพนท(),วาดได()

11/01/61Page 24

ตวอยาง Attributes

คลาส ลกษณะ/ Attributes

นก ปก , ตา , ขา , ปาก , ส

โทรทศน จอ , ขนาด , ส , ป ม

สเหลยม กวาง , ยาว , พนท

Real World

นกใน คอมพวเตอร

11/01/61Page 25

11/01/61Page 26

ตวอยางแอททรบวท

คลาส แอททรบวท

นก ส, เพศ, นาหนก

โทรทศน ยหอ, รน, หมายเลข, ขนาดจอภาพ

สเหลยม ความกวาง, ความสง

PDT : Primitive Data TypeADT : Object

Computer World

11/01/61Page 27

ตวอยางแอททรบวท

คลาส แอททรบวท

พดลม ยหอ ส ความใหญ ขนาด

โทรทศน ยหอ, รน, หมายเลข, ขนาดจอภาพ

สเหลยม ความกวาง, ความสง

PDT : Primitive Data TypeADT : Object

Computer World

Attribute และ Function

11/01/61Page 28

• Real World• Computer World

ปาก ขา ปก

ชอนก ส นาหนก ประเภทนก/ชนด

Attribute และ Function ของคน

11/01/61Page 29

• Real World• Computer World

หว แขน ขา มหวใจ มสมอง

ถาเปนในระบบราน เซเวน

หมายถง พนกงา / เจาหนา / ผจดการ

-ชอ นามสกล ทอย เบอรโทร

-อนๆ

11/01/61Page 30

11/01/61Page 31

11/01/61Page 32

คลาส, วตถ, และเรฟเฟอรเรนซ

• คลาส : วตถ• แบบแปลน : บาน

• หนงคลาสสรางไดหลายวตถ• ใชงานวตถผานทางเรฟเฟอรเรนซ

– รโมทคอนโทรล

11/01/61Page 33

Student

- Name- gender- GPA

สมชาย : Student

- Name = “สมชาย”- gender = “ผชาย”- GPA = “3.15”

Class

Object

การสราง คลาส

class ชอคลาส {แอตทรบวตเมธอด()

}

11/01/61Page 34

class rectangle{private int w;private int h;public void calArea() {…}

}

• class cls_name { ...........} empty class

11/01/61Page 35

Class-name

คน

ธรกมล

การสรางแอตทรบวต

• Modifier type name_attr;

• ตวอยาง• private int Age;

• private doulbe Age;

11/01/61Page 36

PDTADT

Visibility = Modifier

11/01/61Page 37

การสรางวตถ

• รปแบบ– คลาส เรฟเฟอรเรนซ = new คลาส();

• ตวอยางสเหลยม ก = new สเหลยม();สเหลยม ข = new สเหลยม();

Reference คอชอทตงขนเพอใชอางถง

การสรางวตถ ทาได 2 แบบ

นกเรยน อานาจ;อานาจ = new นกเรยน();

11/01/61Page 38

นกเรยน อานาจ = new นกเรยน();

1

2

class student {

}

student s1 = new student();

11/01/61Page 39

Empty Class

class Rectangle {

}

11/01/61Page 40

attributes

class Rectangle {int width;int height;

}

11/01/61Page 41

width

height

attributes

class Rectangle {int width;int height;

}

11/01/61Page 42

width

height

Rectangle

Width : integralHeight : integral

สรางโปรเจกตใหม ชอ Test_Rectangle

11/01/61Page 43

Main program

11/01/61Page 44

• Test• Rectangle

11/01/61Page 45

• Data Member กคอ attributes หรอ ตวแปรของคลาสนนเอง

11/01/61Page 46

สวนประกอบในไฟล Test_rectangle

11/01/61Page 47

Main

rectangle

คลาส rectangle อยในไฟล

เดยวกน กบ

Test_rectangle

สราง เมธอด สาหรบคานวณ พ.ท.

11/01/61Page 48

คลาสถกสราง แตยงใชงานไมได หากตองการ

ใชงาน

ตองสราง อนสแตนซ หรอ ออบเจกต

การสรางเมธอด void

• modifier void method {}• void method {} private• public void• private void• protected void

11/01/61Page 49

TestRectangleMain() Rectangle

- W : integral

+ calArea()

11/01/61Page 50

Rectangle

R: Rectangle

Rectangle R = new Rectangle();

A: Rectangle

Rectangle A = new Rectangle();

11/01/61Page 51

11/01/61Page 52

11/01/61Page 53

Is member of/ instance of

สเหลยม

ก : สเหลยม

ข : สเหลยม

สราง เมธอด สาหรบรบคา width

11/01/61Page 54

สเหลยม

+ กาหนดความกวาง(int w1)

สเหลยม

+ setWidth(int w1)

Getter / setter method

สราง เมธอด สาหรบกาหนดความสง

11/01/61Page 55

สเหลยม

+ กาหนดความกวาง(int w1)+ กาหนดความสง(int h1)

สเหลยม

+ setWidth(int w1)+ setHeight(int h1)

แบบฝกหด

• จงสรางคลาสสามเหลยม และ ออบเจกต สามเหลยม 2 ตว โดยกาหนดความ ฐานและสงของแตละตวดงน– T1 Base = 10.2 Height = 15.6– T2 Base = 8.7 Height = 14.9

– จงวาดแผนภาพคลาส และเขยนโปรแกรม ดวยภาษาจาวา

11/01/61Page 56

11/01/61Page 57

Triangle

T1: Triangle T2: Triangle

- Base : floating-point- Height : floating-point

+ setB(b1 : floating-point) + setH(h1 : floating-point) + getB() : floating-point+ getH() : floating-point+ calArea () : floating-point

- B = 10.2- H = 5.6

- B = 8.7- H =14.3

11/01/61Page 58

11/01/61Page 59

20

5a

20b

10

11/01/61Page 60

Rectangle

a : rectangle b : rectangle

รบความกวาง/สง จากแปนพมพ• คลาส Scanner

11/01/61Page 61

1.

2.

3.

11/01/61Page 62

11/01/61Page 63

สเหลยม

+ กาหนดความกวาง(int w1)+ กาหนดความสง(int h1)

สเหลยม

+ setWidth(int w1)+ setHeight(int h1)+ calArea() : int

A B C ..

Classification abstractions

11/01/61Page 64

• กาหนดความกวาง/ยาว ให สเหลยม ก.

11/01/61Page 65

RUN

11/01/61Page 66

Rectangle

11/01/61Page 67

integer

• byte• short• int• long

11/01/61Page 68

• Byte• Short• Int• Long

Type Wrapper class

long age;byte ageInt age;

int age = 50.3;

Floating-point

• float• double

11/01/61Page 69

• Float• Double

Type Wrapper class

5.8 cm

2.5 cm

Class variables

11/01/61Page 70

rectangle

-Width : int- height : int

Method

11/01/61Page 71

rectangle

-Width : int- height : int

+ setWidth()

rectangle

-Width : int- height : int

+ setWidth(w :integer)

encapsulation

• การนาเอา attribute และ ความสามารถในการจดการกบ attribute รวมเขาดวยกน/ หรอเรยกวา หอหมเขาดวย ทาใหไดคลาสขน

• การหอหมจงมลกษณะคลายเปลอกทมาหอหม • ซงแบงออกเปน 3 แบบ โดยจะเกยวของกบการ

เขาถงขอมล– Public – Private– Protected

11/01/61Page 72

11/01/61Page 73

rectangle

-Width : int- height : int

+ setWidth()

class …… {……attributes // data member……. Methods // method member

}

11/01/61Page 74

Circle

X : intY : intR : int

+ calArea()

คน

class Man {private Arm aArm;private String name;private int age;private Heart aHeart;

}

11/01/61Page 75

Man

-aArm : Arm-aHead : Head-aHeart : Heart-aLeg : aLeg- naame : string- age : int

+ walk()+ eat()+ Speak()

ADT

PDT

Heart

-Siza : int

+ สบฉดเลอด

()

Hair

-no : int

+ ดแล()

คน (computer)

11/01/61Page 76

คน (computer world)Man

-Name : String-Gender : String-BOD : date-Address : String-Tel : String

+ getName()+ setName()+ getBOD()+ setBOD()+ getTel()+ setTel()

11/01/61Page 77

Test_Student :: Tester class

11/01/61Page 78

package

11/01/61Page 79

Student

11/01/61Page 80

Class studentclass student {

private String name;private String Address;private int AGE;private float GPA;private ...... Email;

//--- method member

public void setName(String n) {

name = n;}

}11/01/61Page 81

11/01/61Page 82

ในคลาสทดสอบ tester

• สรางวตถนกเรยน/นกศกษา

11/01/61Page 83

การเรยกใชงาน void method

11/01/61Page 84

11/01/61Page 85

สรางโปรเจกตใหม

11/01/61Page 86

Test_Man

11/01/61Page 87

สราง java class

11/01/61Page 88

Class Man

11/01/61Page 89

11/01/61Page 90

11/01/61Page 91

เพม Method : getName() , setName()

11/01/61Page 92

Overloading Constructor Method

• ชอซากนได • แตตองตางกนท ลาดบ จานวน อากวเมนท ชนดของอากว

เมนท

11/01/61Page 93

Overloading Constructor Method

11/01/61Page 94

11/01/61Page 95

การบญช

Customer c1 = new Customer(5000.0);Customer c1 = new Customer(5000.0);

11/01/61Page 96

constructor

ในกรณ ของเกม สมมต สราง คน จะไอเทม

Method

• Overloading Method• Overriding Method

11/01/61Page 97

Overloading

class Rectangle{

public void calArea() {}public void calArea(int w,int h) {}public void calArea(double w,double h) {}

}

11/01/61Page 98

11/01/61Page 99

Customer

+ deposit(int bal)

+ deposit(double bal)

• คน แบงออกเปน (generalization / specialization abstraction)– นกเรยน– อาจารย

11/01/61Page 100

Man

Student Teacher

Inheritance Inherite

Super Class

Child Class

Reusable

Protected

• คน แบงออกเปน (generalization / specialization abstraction)– นกเรยน– อาจารย

11/01/61Page 101

Man

Student Teacher

Inherit Inherit

Super Class

Child Class

Reusable

-Name : String# surname : String

Protected

• คน แบงออกเปน (generalization / specialization abstraction)– นกเรยน– อาจารย

11/01/61Page 102

Man

Student Teacher

Inherit Inherit

Super Class

Child Class

Reusable

Name : Stringsurname : String

Inheritance in java

• class A extends B {

• }

11/01/61Page 103

B

A

11/01/61Page 104

Man

Student

11/01/61Page 105

11/01/61Page 106

student

Man

student

Man

Man

Student

Man

Student

11/01/61Page 107

11/01/61Page 108

Man

Man

Test_Man

11/01/61Page 109

ตอนทคนเกดมา จะถกตงชอ

ตอมาเมอเตบโตขนกจะ

สามารถเปลยนชอได

11/01/61Page 110

11/01/61Page 111

rectangle

-Width : int- height : int

+ setWidth()+ setHeight()

แนวขอสอบระหวางภาค 1/2558

• 1. แสดงเมน– 1. คานวณสเหลยม– 2. คานวณสามเหลยม– 3......

– ถาเลอก สามเหลยม รบ – 2.1 .....– 2.2 .... แลวคานวณ

11/01/61Page 112

คลาส

วตถ

Scanner

สราง เมธอดทมการคนคา

11/01/61Page 113

สรางวตถ คอ instance

11/01/61Page 114

11/01/61Page 115

11/01/61Page 116

ประกาศ R1 เปน Rectangle

11/01/61Page 117

การเรยกใชงานเมธอด ผานออบเจกต

11/01/61Page 118

11/01/61Page 119

X = R1.CalArea();

11/01/61Page 120

Triangle

11/01/61Page 121

Package Test_rectangle

11/01/61Page 122

Test_Rectangle.java

Rectangle.java

Triangle.java

• สราง data member

11/01/61Page 123

11/01/61Page 124

Triangle

-Base : float-Height : float

+ setBase()+ setHeight(h : floating-poin

11/01/61Page 125

สรางอนสแตนซของคลาส Triangle

11/01/61Page 126

การกาหนด Modifier แบบ public

11/01/61Page 127

Modifier/Accessibility

• Default• Private• Public• Protected

11/01/61Page 128

Information Hiding / Encapsulation

Default Modifier : Package

11/01/61Page 129

11/01/61Page 130

ขอความและเมธอด

• สงใหวตถทางานโดยการสงขอความ (message) หรอคาสงไปหาวตถ

• เมอวตถไดรบขอความแลว วตถนนกจะทางานตามวธการหรอคาสงตางๆทเขยนไวในเมธอด (method)

11/01/61Page 131

การเรยกเมธอด (การสงขอความ)

• รปแบบ– เรฟเฟอรเรนซ.เมธอด();

• ตวอยางสเหลยม ส = new สเหลยม();System.out.println( ส.คานวณพนท() );

การสอสารกนระหวางวตถ จะใชงานผานทางเมธอด

11/01/61Page 132

การประกาศเมธอด

class สเหลยม {double คานวณพนท() {

// คานวณหาพนทของสเหลยม …

}}

11/01/61Page 133

เมธอดทคนคาเปนชนดขอมลพนฐาน

class สเหลยม {double คานวณพนท() {

// คานวณหาพนทของสเหลยม …// สงคนคาพนทใหกบผเรยกreturn พนทของสเหลยม;

}}

11/01/61Page 134

เมธอดทคนคาเปนเรฟเฟอรเรนซ

class สเหลยม {String ขอขอมล() {

…return สตรงทแสดงขอมลสเหลยม;

}}

11/01/61Page 135

เมธอดทไมคนคา

class สเหลยม {void เพมขนาดสองเทา() {

…return;

}}

11/01/61Page 136

แอททรบวท

• ขอมลทใชอธบายความแตกตางของวตถ – เชน วตถแมว มชอ ส พนธ นาหนก แตกตางกน

• ตวแปรวตถ (instance variable)

11/01/61Page 137

แอททรบวท

class สเหลยม {double ความกวาง;double ความสง;

}

11/01/61Page 138

การใชงานแอททรบวท

• รปแบบ– เรฟเฟอรเรนซ.แอททรบวท

• ตวอยางสเหลยม ส = new สเหลยม();ส.ความกวาง = 10;ส.ความสง = 5;

11/01/61Page 139

คอนสตรคเตอร (constructor)

• เมธอดทมช อเหมอนกบคลาส • ใชกาหนดคาเรมตนใหกบแอททรบวต • ถกเรยกใชเมอเราสรางวตถดวยคาสง new

11/01/61Page 140

การประกาศคอนสตรคเตอร

class สเหลยม {สเหลยม(double ก, double ส) {

ความกวาง = ก;ความสง = ส;

}

double ความกวาง;double ความสง;

}

11/01/61Page 141

การเรยกคอนสตรคเตอร

สเหลยม ก = new สเหลยม(10, 5);สเหลยม ข = new สเหลยม(20, 4);System.out.println(ก.กวาง);System.out.println(ข.กวาง);

11/01/61Page 142

การโอเวอรโหลดเมธอด (Overload)

class สเหลยม {{

สเหลยม() { ... }สเหลยม(double ก, double ส) { ... }

}

11/01/61Page 143

การโอเวอรโหลดเมธอด

class สเหลยม {{

double getArea() { ... }int getArea(int n) { ... }

}

11/01/61Page 144

แปลงไทยจาวาเปนจาวา

11/01/61Page 145

ประกาศคลาส

class สเหลยม {

}

class Rectangle {

}

11/01/61Page 146

เพมเมธอด

class สเหลยม {double คานวณพนท() {

.... }

}

class Rectangle {double getArea() {

.... }

}

11/01/61Page 147

เพมแอททรบวท

class สเหลยม {double คานวณพนท() {

.... }double ความกวาง;double ความสง;

}

class Rectangle {double getArea() {

.... }double width;double height;

}

11/01/61Page 148

เขยนวธการทางานของเมธอด คานวณพนท()

class สเหลยม {double คานวณพนท() {

return ความกวาง * ความสง;

}double ความกวาง;double ความสง;

}

class Rectangle {double getArea() {

return width * height;

}double width;double height;

}

11/01/61Page 149

เขยนคอนสตรคเตอร

class สเหลยม {สเหลยม(double ก, double ส) {

ความกวาง = ก;ความสง = ส;

}

...}

class Rectangle {Rectangle(double w,double h) {

width = w;height = h;

}...

}

11/01/61Page 150

ทดสอบคลาส Rectangle

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

Rectangle r = new Rectangle(2, 3);System.out.println(r.getArea());

Rectangle p = new Rectangle(5, 7);System.out.println(p.getArea());

}}

11/01/61Page 151

คอมไพลและรน

11/01/61Page 152

เมธอด toString()

• พมพขอมลเกยวกบวตถ

class Rectangle {public String toString() {

String result = "Width = " + width;result += " Height = " + height;return result;

}...

}

toString ของ Student

11/01/61Page 153

ผลการรน

11/01/61Page 154

11/01/61Page 155

การเรยกเมธอด toString()

• System.out.println( rect.toString() );• System.out.println( rect );

System.out.println( R1.toString() );

11/01/61Page 156

เมธอด equals()

• เปรยบเทยบแอททรบวท• ไมใชเครองหมาย == เพอเปรยบเทยบวตถ

class Rectangle {public boolean equals(Rectangle other) {

return (width == other.width) && (height == other.height);}...

}

ผลการรน

11/01/61Page 157

11/01/61Page 158

11/01/61Page 159

คาประกอบ (modifiers)

11/01/61Page 160

คาประกอบการเขาใช

• ประกอบกบการประกาศแอททรบวตหรอเมธอด • private

– วตถตางคลาสไมสามารถเขาใชได – การปกปองขอมลทาได – มกจะใหแอททรบวทมการเขาใชแบบ private

• public– อนญาตใหคลาสอนใชได – มกจะใหเมธอดมการเขาใชแบบ public

11/01/61Page 161

คาประกอบการเขาใช

class Rectangle {public double getArea() {

return width * height;

}private double width;private double height;

}

11/01/61Page 162

ทดลองเขาใชแอททรบวททถกปกปอง

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

Rectangle rect = new Rectangle();rect.width = 10;

}}

11/01/61Page 163

ทดลองเขาใชแอททรบวททถกปกปอง

11/01/61Page 164

ทาไมเราควรกาหนดการปกปองแอททรบวท

• ความเปนสวนตวสามารถปองกนวตถอนๆเขามาทาลายคณสมบตบางอยาง – เลขบญชธนาคารตดลบแทนทจะเปนเลขศนยหรอเลข

บวก – ความกวางและความสงของสเหลยมนอยกวาหรอเทากบ

ศนย

• ทาใหเราสามารถเปลยนแปลงชนดของตวแปรเหลานนได โดยไมกระทบกระเทอนคลาสอนทใช คลาสของเรา

11/01/61Page 165

การซอนวธการทางาน

• สามารถเปลยนแปลงวธการทางานของวตถไดโดยไมกระทบตอผใชวตถ

• เกดความยดหยน – เชน ถาเปรยบวตถเหมอนกบรถ และผใชวตถคอคนขบรถ

บรษทผผลตรถสามารถเปลยนเครองยนตรนใหม เปลยนระบบเบรค ฯลฯ โดยทคนขบยงสามารถขบรถได เหมอนเดม

Information hiding

11/01/61Page 166

สเหลยมทผดปกต

• Rectangle rect = new Rectangle( -10, 10);• IllegalArgumentException

11/01/61Page 167

การแจงวามความผดปกต

class Rectangle {public Rectangle(double w, double h) {

if (w <= 0 || h <= 0)throw new IllegalArgumentException();

width = w;height = h;

}...

}

11/01/61Page 168

การแจงวามความผดปกต

11/01/61Page 169

การเขาใชแบบอนๆ

• protected– เกยวของกบการสบทอด

• การเขาใชแบบแพคเกจ (package)– แพคเกจเปนทเกบรวมรวมคลาสทเกยวของกน – แพคเกจเปรยบไดกบโฟลเดอร– การเขาใชแบบแพคเกจไมตองใชคาประกอบใดๆ

11/01/61Page 170

สแตตกเมธอด (static method)

• เมธอดของคลาส• รปแบบการประกาศ

– public static ชนดขอมลทสงกลบ เมธอด(พารามเตอร) { … }

• รปแบบการเรยกใช – คลาส.สแตตกเมธอด(พารามเตอร )

• ตวอยางการเรยกใช – int m = Math.round(12.5); – int n = String.valueOf(1234);

11/01/61Page 171

ตวแปรของคลาส

• รปแบบ– private static ชนดขอมล ตวแปร;

• ตวอยาง– private static int count;

11/01/61Page 172

คาคงทของคลาส

• รปแบบ– public static final ชนดขอมล ตวแปร=คา;

• ตวอยาง– public static final int TOTAL_SIDES = 4;

11/01/61Page 173

Enum

11/01/61Page 174

อนม

• ชนดขอมลทสรางขนใหม• มคา (value) ทเปนไปไดอยไมกคา

– คลาสสรางวตถไดมากมาย

• อนมมวตถนอย– อนม เกรด มไดเพยง 5 คา คอ A, B, C, D, F– อนม เพศ มไดเพยง 2 คา คอ ชาย, หญง – อนม สสญญาณไฟ มไดเพยง 3 คา คอ แดง, เหลอง,

เขยว

11/01/61Page 175

การประกาศอนม

• รปแบบ– enum อนม { คา1, คา2, ...}

• ตวอยาง– enum Grade { A, B, C, D, F }

11/01/61Page 176

การพมพคาทกคาในอนม

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

for (Grade grade : Grade.values()) {System.out.println(grade);

}}

}

11/01/61Page 177

ตวแปรชนดอนม

public class Enum {enum Grade { A, B, C, D, F }

public static void main(String[] args) {Grade myGrade = Grade.A;

System.out.println(myGrade);}

}

11/01/61Page 178

การกาหนดคาอนๆใหกบตวแปรอนม

public class Enum {enum Grade { A, B, C, D, F }

public static void main(String[] args) {Grade myGrade = Grade.A;

myGrade = 'Z'; //myGrade = Grade.Z; //

System.out.println(myGrade);}

}

11/01/61Page 179

เมธอด

• อนมสามารถมเมธอดไดเหมอนกบคลาส• การเรยกใชเมธอดทาโดยผานตวแปรอนม

11/01/61Page 180

อนมสญญาณไฟจราจร

public enum TrafficLight {

RED, GREEN, YELLOW;

public TrafficLight next() {

switch(this) {

case RED: return GREEN;

case GREEN: return YELLOW;

default: return RED;

}

}

}

11/01/61Page 181

ทดสอบไฟจราจรpublic class Test {

public static void main(String[] args) {TrafficLight t = TrafficLight.RED;System.out.println(t);t = t.next();System.out.println(t);t = t.next();System.out.println(t);

TrafficLight u = TrafficLight.YELLOW;System.out.println(u.next());

}}

Test_traffficLight

11/01/61Page 182

11/01/61Page 183

Package

11/01/61Page 184

แพคเกจ

• เปรยบไดกบโฟลเดอร • ประโยชน

– จดระเบยบคลาส– แกปญหาคลาสชอซากน

11/01/61Page 185

การนาคลาสไปใสในแพคเกจ

• รปแบบ– package แพคเกจ;

• ตวอยางpackage somchai;

public class Rectangle {...

}

11/01/61Page 186

การนาคลาสไปใสในแพคเกจยอย

• รปแบบ– package แพคเกจ.แพคเกจยอย ;

• ตวอยางpackage somchai.shape;

public class Triangle {...

}

11/01/61Page 187

การตงชอแพคเกจ

• นยมตงเปนโดเมนเนมยอนหลง– com.mycompany– th.in.somchai

• ตอดวยชอแพคเกจยอย– th.in.somchai.shape

11/01/61Page 188

การอางถงคลาสทอยในแพคเกจ

• สาหรบคลาสในแพคเกจเดยวกน– ใชชอคลาส

• สาหรบคลาสทอยตางแพคเกจ– รปแบบ

• แพคเกจ.คลาส;

– ตวอยางsomchai.Rectangle r;r = new somchai.Rectangle()

11/01/61Page 189

ตวอยาง: คลาสสเหลยมในแพคเกจสมชาย

package somchai;

public class Rectangle {public void say() {

System.out.println("I'm a rectangle");}

}

11/01/61Page 190

การอางถงคลาสทอยในแพคเกจ

package somchai;

public class TestRectangle {public static void main(String[] a){

Rectangle r;r = new Rectangle();r.say();

}}

package somying;

public class TestRectangle {public static void main(String[] a){

somchai.Rectangle r;r = new somchai.Rectangle();r.say();

}}

11/01/61Page 191

การอมพอรตคลาสจากแพคเกจอน

• ขอดคอไมตองเขยนชอเตม

11/01/61Page 192

การอมพอรตคลาส

• รปแบบ– import แพคเกจ.คลาส;– import แพคเกจ.*;

• ตวอยางimport somchai.Rectangle;import somchai.*;

11/01/61Page 193

ตวอยางการอมพอรตคลาสสเหลยม

package somying;

public class TestRectangle {public static void main(String[] a){

somchai.Rectangle r;r = new somchai.Rectangle();r.say();

}}

package somying;import somchai.*;

public class TestRectangle {public static void main(String[] a){

Rectangle r;r = new Rectangle();r.say();

}}

11/01/61Page 194

โฟลเดอรทใชเกบคลาส

• คลาส Rectangle อยในแพคเกจ somchai ดงนนไฟล Rectangle.java ควรอยในโฟลเดอร somchai

• คลาส TestRectangle อยในแพคเกจ somyingดงนนไฟล TestRectangle.java ควรอยในโฟลเดอร somying

11/01/61Page 195

การคอมไพลและรน

11/01/61Page 196

ผลการคอมไพล

• การคอมไพลไฟลซอรสโคดดวยคาสงในหนาทแลว ทาใหเกดไฟลไบตโคดในโฟลเดอรเดยวกน

11/01/61Page 197

แยกไฟล .java กบ .class

• สรางโฟลเดอรชอ src เพอเกบซอรสโคด • สรางโฟลเดอรชอ classes เพอเกบไบตโคด• ใชคาสงตอไปนในโฟลเดอร src

11/01/61Page 198

ออปชนการคอมไพลและรน

• การคอมไพลดวยออปชน -d หมายถงใหสรางไบตโคดในโฟลเดอรทกาหนด ในทนคอ ..\classes

• การรนดวยออปชน -cp หมายถงใหเครองจกรเสมอนจาวาหาคลาส (ไบตโคด) ในโฟลเดอรทกาหนด ในทนคอ ..\classes

11/01/61Page 199

ทดลองตดออกทละคาและศกษาความหมาย

package somchai;public class Rectangle {

public void say() {System.out.println("I'm a rectangle");

}}

11/01/61Page 200

แพคเกจไรชอ (default package)

package somchai;public class Rectangle {

public void say() {System.out.println("I'm a rectangle");

}}

• ไมสามารถอมพอรตคลาสจากแพคเกจไรชอได

11/01/61Page 201

แพคเกจไรชอ

public class TestRectangle {public static void main(String[] a){

Rectangle r;r = new Rectangle();r.say();

}}

package somying;

public class TestRectangle {public static void main(String[] a){

Rectangle r;r = new Rectangle();r.say();

}}

11/01/61Page 202

คลาสทใชไดภายในแพคเกจ

package somchai;public class Rectangle {

public void say() {System.out.println("I'm a rectangle");

}}

• คลาสในแพคเกจเดยวกนเทานนทสามารถเรยกใชได

11/01/61Page 203

คลาสทใชไดภายในแพคเกจ

package somchai;

public class TestRectangle {public static void main(String[] a){

Rectangle r;r = new Rectangle();r.say();

}}

package somying;import somchai.*;

public class TestRectangle {public static void main(String[] a){

Rectangle r;r = new Rectangle();r.say();

}}

11/01/61Page 204

การเขาใชแบบแพคเกจ

package somchai;public class Rectangle {

public void say() {System.out.println("I'm a rectangle");

}}

• คลาสในแพคเกจเดยวกนเทานนทสามารถเรยกใชได

11/01/61Page 205

ตวอยางการอมพอรตคลาสสเหลยม

package somchai;

public class TestRectangle {public static void main(String[] a){

Rectangle r;r = new Rectangle();r.say();

}}

package somying;import somchai.*;

public class TestRectangle {public static void main(String[] a){

Rectangle r;r = new Rectangle();r.say();

}}

11/01/61Page 206

แพคเกจทจาวาจดให

• จาวารน 5.0 มคลาสและอนเตอรเฟซรวมกนถง 3,279 อน

• จดหมวดหมไวเปนแพคเกจจานวน 166 แพคเกจ

11/01/61Page 207

แพคเกจทจาวาจดให

11/01/61Page 208

แพคเกจทเปนพนฐานของภาษาจาวา

• java.lang มคลาสทเราใชกนประจาไดแก String, StringBuffer และ Math – คลาสตางๆ ในแพคเกจนสามารถเรยกใชไดโดยไมตองอมพอรต

• java.util มคอลเลคชนคลาสซงใชในการเกบวตถอนๆ คลาสทจดการเกยวกบวนเวลา และคลาสอรรถประโยชนอนๆ

• java.awt และ javax.swing มคลาสสาหรบสรางสวนตดตอกบผใชแบบกราฟก

• java.applet มคลาสสาหรบใชสรางจาวาแอพเพลต

11/01/61Page 209

การอมพอรตสแตตกแอททรบวทและเมธอด

11/01/61Page 210

อมพอรตสแตตก

• อมพอรตแอททรบวทหรอเมธอดของคลาส (staticattributes and methods)

• รปแบบ– import static แพคเกจ.คลาส.คาคงทของคลาส;– import static แพคเกจ.คลาส.เมธอดของคลาส;

11/01/61Page 211

อมพอรตสแตตก

• ตวอยางimport static java.lang.Math.PI;import static java.lang.Math.cos;

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

System.out.println(cos(PI));}

}

11/01/61Page 212

Interface

11/01/61Page 213

อนเทอรเฟซ

• วตถตางคลาสกน อาจจะมความสามารถบางอยางทเหมอนกน

• เชน นกและเครองบนเปนวตถทตางประเภทกน แตทงคกสามารถบนไดเหมอนกน

• จดใหคลาสนกและเครองบนอยในกลมเดยวกน• เรยกกลมของคลาสทมความสามารถเหมอนกนวาม

อนเทอรเฟซ แบบเดยวกน

11/01/61Page 214

อนเทอรเฟซ บนได

interface บนได {บน();

}

11/01/61Page 215

อมพลเมนต

class นก implements บนได {บน( ) {

// วธการบนของนก}

}class เครองบน implements บนได {

บน( ) {// วธการบนของเครองบน

}}

11/01/61Page 216

การใชงานอนเทอรเฟซ

• ประกาศเรฟเฟอรเรนซ– บนได บ;

• สรางและอางถงวตถ– บ = new นก();

• เรยกใชเมธอดทประกาศในอนเทอรเฟซ– บ.บน();

11/01/61Page 217

เรฟเฟอรเรนซทอางถงวตถตางคลาส

บนได บ;

บ = new นก();บ = new เครองบน();

บ.บน();

11/01/61Page 218

พอลมอรฟซม (polymorphism)

บนได บ;บ = new นก();บ.บน();บ = new เครองบน();บ.บน();

• คาสงแบบเดยว แตไปทางานทเมธอดทแตกตางกน

11/01/61Page 219

เรฟเฟอรเรนซไมสามารถเรยกใชไดทกเมธอด

บนได บ = new นก();บ.จก();

บนได ค = new เครองบน( );ค.จก( );

11/01/61Page 220

อนเทอรเฟซทมมากกวาหนงเมธอด

interface บนได {บน();รอนลง();

}

class นก implements บนได {บน( ) {

// วธการบนของนก}รอนลง( ) {

// วธการรอนลงของนก}

}

11/01/61Page 221

อมพลเมนตมากกวาหนงอนเทอรเฟซ

interface รองเพลงได {รองเพลง( );

}

class นก implements บนได , รองเพลงได {บน( ) { ไทยจาวา

// วธการบนของนก}รอนลง( ) {

// วธการรอนลงของนก}รองเพลง( ){

// วธการรองเพลงของนก}

}

11/01/61Page 222

11/01/61Page 223

คาคงท

11/01/61Page 224

คาคงท

interface บนได {int เพดานบน = 1000;void บน( );void รอนลง( );

}

11/01/61Page 225

คาคงท

interface บนได {public static final int เพดานบน = 1000;void บน( );void รอนลง( );

}

11/01/61Page 226

การอานคาคงท

• คลาสทอมพลเมนตอนเทอรเฟซ บนได เขยนแค เพดานบน

• คลาสอนทไมเกยวของกบอนเทอรเฟซนตองเขยนชอเตมคอ บนได.เพดานบน

11/01/61Page 227

สรางอนเทอรเฟซดวยภาษาจาวา

11/01/61Page 228

อนเทอรเฟซ 'ตราคาได' (Priceable)

• กลมของคลาสทเปนสนคาในราน • เมธอด getPrice( )

11/01/61Page 229

อนเทอรเฟซ 'ตราคาได' (Priceable)

public interface Priceable {int getPrice();

}

11/01/61Page 230

คลาสไมจมฟน

• ชนละ 100 บาท

11/01/61Page 231

คลาสไมจมฟน

public class Toothpick implements Priceable {public int getPrice() {

return 100;}

}

11/01/61Page 232

ทดสอบคลาสไมจมฟน

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

Priceable item = new Toothpick();System.out.println(item.getPrice());

}}

11/01/61Page 233

คลาสเรอรบ

• วธคดราคาทซบซอนขน• เรอรบลาใหมจะมราคาหนงลานบาท • เรอรบทใชแลวราคาจะลดลงไปปละแสนบาท แต

ราคาจะไมตากวา 10,000 บาท

11/01/61Page 234

คลาสเรอรบ

public class BattleShip implements Priceable {public int getPrice() {

int deprecation = age * 100000;return Math.max(originalPrice - deprecation, 10000);

}public void setAge(int year) {

age = year;}int originalPrice = 1000000;int age = 0;

}

11/01/61Page 235

ทดสอบคลาสเรอรบ

public class TestPriceable2 {

public static void main(String[] args) {BattleShip ship = new BattleShip();ship.setAge(3);

Priceable item = ship;System.out.println(item.getPrice());

}}

11/01/61Page 236

คลาสรถเขน

• คานวณราคาสนคา (Priceable) ทงหมดทอยในรถเขน

• เกบสนคาได 2 ชน

11/01/61Page 237

คลาสรถเขน

public class Cart {Priceable[] items = new Priceable[2];

public int sumPrice() {int sum;sum = items[0].getPrice() + items[1].getPrice();return sum;

}}

11/01/61Page 238

ทดสอบคลาสรถเขน

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

Toothpick toothpick = new Toothpick();BattleShip ship = new BattleShip();ship.setAge(3);

Cart cart = new Cart();cart.items[0] = toothpick ;cart.items[1] = ship;System.out.println(cart.sumPrice());

}}

11/01/61Page 239

อนเทอรเฟซกบการนากลบมาใชใหม

• ในอนาคต ทางรานตองการขายลง • เขากจะนาลงมาอยในกลมของสงทตราคาได • สามารถนาลงมาใสในรถเขนและคดราคาไดโดยไม

ตองไปแกไขคลาสรถเขน

Cart cart = new Cart();cart.items[0] = monkey;cart.items[1] = toothpick;

System.out.println(cart.sumPrice());

11/01/61Page 240

interface Comparable<T>

• int compareTo(T o)– a negative integer : this < o– zero : this = o– a positive integer : this > o

11/01/61Page 241

ตวอยาง Person

• เปรยบเทยบเงนเดอน

11/01/61Page 242

Inheritance

11/01/61Page 243

การสบทอด (inheritance)

• เลยนแบบการสบทอดลกษณะของลกจากพอและแม

• ขยายความสามารถของคลาสแม• เปลยนแปลงการทางานของคลาสแม

11/01/61Page 244

การสบทอด

• รปแบบ– class คลาสลก extends คลาสแม

• ตวอยางclass แมว extends สตว { }class ปลา extends สตว { }class ลง extends สตว {}

มคลาสแมไดแคคลาสเดยว

11/01/61Page 245

วตถในคลาสลกสามารถทางานตามเมธอดของคลาสแมได

ลง ล = new ลง();ล.กน();

11/01/61Page 246

เพมเมธอดในคลาสลก

class ลง extends สตว {// เมธอดทเพมเขามาเกบลกมะพราว() { … }

}ลง ล = new ลง();ล.เกบลกมะพราว();สตว ส = new สตว();ส.เกบลกมะพราว();

11/01/61Page 247

เพมแอททรบวทในคลาสลก

class ปลา extends สตว {// แอตทรบวตทเพมเขามา ชอ;

}

11/01/61Page 248

พอลมอรฟซม (Polymorphism)

11/01/61Page 249

การโอเวอรไรดเมธอด (override)

class ปลา extends สตว {// แอตทรบวตชอ;

// เมธอดนอน() {

// วธการนอนของปลา…

}}

11/01/61Page 250

พอลมอรฟซม

11/01/61Page 251

ความหมาย

• poly แปลวาหลายหรอมาก • morphism นนมาจากคาวา morph ซงแปลวา

รปราง• รวมกนแลวหมายถงความสามารถทส งหนงจะมได

หลายรปราง ซงเมอใชคานกบการโปรแกรมเชงวตถ กจะหมายถงการทคาสงแบบเดยวกนสามารถถกแปลไดหลายแบบ

11/01/61Page 252

พอลมอรฟซมกบการนากลบมาใชใหม

• พอลมอรฟซมสนบสนน การนากลบมาใชใหม(reuse)

• ถาเราไดเขยนโปรแกรมทใชงานไดกบสตว โปรแกรมของเรายอมใชไดกบแมว ปลา และลงนอกจากนนถามคนสรางคลาสอกวนาขนมาใหม โปรแกรมทเราเขยนกสามารถใชไดกบคลาสอกวนาเชนกน

11/01/61Page 253

การสบทอดในภาษาจาวา

11/01/61Page 254

คลาสรปรางและคลาสทสบทอด

11/01/61Page 255

คลาสรปราง

• รปรางเปนรปทอยในระนาบสองมต • มพนท

– เมธอด getArea() ใชคานวณหาพนทของรปราง

• มส– public enum Color { Red, Green, Blue } – เมธอด getColor()

11/01/61Page 256

คลาสรปราง

public class Shape {public Shape() { color = Color.Red; }

public double getArea() { return 0; }

public void setColor(Color c) { color = c; } public Color getColor() { return color; }

private Color color;}

11/01/61Page 257

ทดสอบคลาสรปราง

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

Shape s1 = new Shape();System.out.println(s1.getColor());System.out.println(s1.getArea());

Shape s2 = new Shape();s2.setColor(Color.Blue);System.out.println(s2.getColor());System.out.println(s2.getArea());

}}

11/01/61Page 258

คอมไพลและรน

11/01/61Page 259

คลาสสเหลยมผนผา

class Rectangle extends Shape {...public double getArea() {

return width * height;}

}

11/01/61Page 260

คลาส Object

11/01/61Page 261

เมธอด toString()

public class Rectangle extends Shape {...

@Overridepublic String toString() {

String str = "Rectangle";str += " color=" + getColor();str += " width=" + width;str += " height=" + height;str += " area=" + getArea();return str;

}}

11/01/61Page 262

เมธอด toString()

• เปนเมธอดทถกโอเวอรไรดจากคลาส Object

11/01/61Page 263

คลาส Object

• แมของทกคลาส• เมธอดทนาสนใจ

– toString()– equals()– clone() – hashCode()

11/01/61Page 264

เมธอด equals()

@Override public boolean equals(Object otherObject) {

if (otherObject instanceof Rectangle) { Rectangle otherRect = (Rectangle) otherObject;

boolean equalWidth = width == otherRect.width;boolean equalHeight = height == otherRect.height;

return equalWidth && equalHeight;}return false;

}

11/01/61Page 265

เมธอด hashCode()

• จะสงจานวนเตมทเปนรหสแฮช เพอการคนหาขอมลทรวดเรว

@Overridepublic int hashCode() {

return (int) (width + height * 17);}

11/01/61Page 266

เมธอด clone()

สรางวตถทเหมอนกบวตถทไดรบขอความ

@Overridepublic Object clone() {

Rectangle clone = new Rectangle(width, height);return clone;

}

11/01/61Page 267

ทดสอบเมธอดทโอเวอรไรดจากคลาส Object

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

Rectangle r1 = new Rectangle(2, 5);System.out.println(r1);System.out.println(r1.hashCode());

Rectangle r2 = new Rectangle(5, 2);System.out.println(r1.equals(r2));

Rectangle r3 = (Rectangle) r1.clone();System.out.println(r1.equals(r3));

}}

11/01/61Page 268

สรปเมธอดในคลาสสเหลยมผนผา

11/01/61Page 269

การหามโอเวอรไรด

11/01/61Page 270

คลาสสเหลยมจตรส

public class Square extends Rectangle {public Square( double w) {

super(w,w);}...

}

11/01/61Page 271

ไฟนอลคลาส

• ไมสามารถถกสบทอดได

public final class Square

11/01/61Page 272

ไฟนอลเมธอด

• ไมสามารถถกโอเวอรไรดได

public class Shape {public final Color getColor() {

return color;}...

}

11/01/61Page 273

การเขาใชแบบ protected

11/01/61Page 274

การเขาใชแบบ protected

• คลาสลกสามารถใชเมธอดและแอททรบวททมการเขาใชแบบ protected ได

• คลาสทอยในแพคเกจเดยวกนกสามารถใชเมธอดและแอททรบวททมการเขาใชแบบ protected ได

• การเขาใชแบบนมความเขมงวดนอยกวาแบบprivate ซงหามคลาสอนใดเขาใช แตกอสระนอยกวาแบบ public ทใครๆกสามารถเขาใชได

11/01/61Page 275

การเขาใชแบบ protected

11/01/61Page 276

คลาสวงกลม

public class Circle extends Shape {protected double radius;

public Circle(double r) {radius = r;

}

public double getRadius() {return radius;

}...

}

11/01/61Page 277

คานวณพนทของวงแหวน

public class Ring1 extends Circle {public double getArea() {

double outerArea = Math.PI * radius * radius; double innerArea = Math.PI * innerRadius * innerRadius; return outerArea - innerArea;

}...

}

11/01/61Page 278

คานวณพนทของวงแหวน

public class Ring2 extends Circle {public double getArea() {

double outerArea = super.getArea();double innerArea = Math.PI * innerRadius * innerRadius; return outerArea - innerArea;

}...

}

11/01/61Page 279

แอบสแตรกทคลาส (abstract class)

11/01/61Page 280

คลาสทประกาศขนมาลอยๆ (Abstract Class)

• เมธอด getArea() ในคลาส Shape ไมควรสงคาศนยหรอคาใดๆกลบมา ทงนเพราะวาเราไมทราบวธคานวณหาพนทของวตถ Shape

public abstract double getArea();

• เมธอดทถกประกาศขนมาลอยๆ (abstract) นตองอยในคลาสทเปน abstract ดวยเชนกน คลาส Shape เขยนใหมไดดงน

public abstract class Shape {public abstract double getArea();...

}

11/01/61Page 281

การใชงาน abstract class

• ไมสามารถสรางวตถในคลาสนได Shape s = new Shape();

• แตอางถงวตถในคลาสลกได Shape s;s = new Rectangle(3,2);s = new Square(5);

11/01/61Page 282

พอลมอรฟซม

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

Shape shape;

shape = new Rectangle(10, 20);System.out.println(shape.getArea());

shape = new Circle(10);System.out.println(shape.getArea());

}}

11/01/61Page 283

การนามาใชอก

public class ShapeArray {public static double sumArea(Shape[] shapes) {

double sum = 0;for( Shape s : shapes) {

sum += s.getArea();} return sum;

}}

11/01/61Page 284

การนามาใชอก

Shape[] s = new Shape[3];s[0] = new Triangle(10);s[1] = new Rectangle(10,20);s[2] = new Pentagon(20);

double d = ShapeArray.sumArea(s);

11/01/61Page 285

ขอดขอเสยของการสบทอด

11/01/61Page 286

ขอดของการสบทอด

• การนากลบมาใชใหม – ถาเราตองการสรางคลาสทมความสามารถคลายๆกบคลาสทมอย

แลว – เราอาจจะใชการสบทอดแทนทจะเขยนขนมาใหมหมด

• ความเปนมาตรฐานเดยวกน – คลาสพนฐานเปนการกาหนดโครงแบบในการระบความสามารถของ

วตถในคลาสลก

• เขาใจสาระสาคญไดงาย

11/01/61Page 287

ขอเสยของการสบทอด

• โปรแกรมทางานชาลง – มคาใชจาย (overhead) ในคนหาและเรยกใชเมธอดของคลาสทสบ

ทอด – แตคาใชจายดงกลาวถอวานอยมากเมอเทยบกบประโยชนทไดรบ

จากการสบทอด

• โปรแกรมมขนาดใหญขน – แตหนวยความจาราคาไมแพง

• ความซบซอนเพมขน – ผใชตองหาตามคลาสตางๆ ทอยในผงการสบทอดจนกวาจะพบ

คลาสทอมพลเมนตเมธอดนน ปญหาทกลาวถงนมช อวาปญหาลกดง (Yo-yo problem)

11/01/61Page 288

Composition

• ม Counter• สราง CounterUpDown

– class CounterUpDown extends Counterหรอ

– class CounterUpDown {Counter c;....

}

11/01/61Page 289

Generics

11/01/61Page 290

หวขอ

• นยามและประโยชน• ตวอยาง

– คลาส Pair– คลาส Stack

• Generic array creation• Generic Method• Bounded Type• Wildcard

11/01/61Page 291

นยามและประโยชน

11/01/61Page 292

Generics

• Generics is essentially the ability to have type parameters on your type.

• They are also called parameterized types or parametric polymorphism

11/01/61Page 293

ประโยชน

• เขยนคลาสเพยงเวอรชนเดยว– List<E> vs ListOfInteger, ListOfString, etc

• type safety– คอมไพเลอรสามารถตรวจสอบประเภทขอมลได

List<Integer> list = new ArrayList<Integer>();list.add(10);String s = list.get(0); // compile fails

• โคดอานงาย– ไมตอง cast

11/01/61Page 294

ใชระบประเภทของวตถทcollection ใชเกบ

List<String> list = new ArrayList();String s1 = "hello";StringBuffer sb = new StringBuffer("hello");list.add("hello");list.add(sb); // won't compile

11/01/61Page 295

ตวอยาง

11/01/61Page 296

คลาส Pair

public final class Pair<X, Y> {private X first;private Y second;public Pair(X first, Y second) {

this.first = first;this.second = second;

}public X getFirst() {

return first;} public Y getSecond() {

return second;}

}

11/01/61Page 297

ทดสอบคลาส Pair

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

Pair<Integer, String> pair;pair = new Pair(10, "somchai");System.out.println(pair.getFirst());System.out.println(pair.getSecond());

Pair<String, String> name;name = new Pair("somchai", "brown");System.out.println(name.getFirst());System.out.println(name.getSecond());

}}

11/01/61Page 298

Stack

public class Stack<E> {

E items[];

int count;

void push(E e) {

items[count++] = e;

}E pop() {

return items[--count];

}...

}

11/01/61Page 299

Stack

public class Stack<E> {

static final int MAX_ITEM = 32;

Stack() {

Object[] objects = new Object[MAX_ITEM];

items = (E[]) objects;

count = 0;}

...

}

11/01/61Page 300

การใชงาน

11/01/61Page 301

Generic Array Creation

import java.util.*;

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

List<String> [] lists;lists = new List<String>[10]; // compile fails

}}

11/01/61Page 302

เหตผลทหามสรางอารเรยของ genericpackage genericarray;

import java.util.*;

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

List<String>[] arrayOfListOfString = null;// arrayOfListOfString = new ArrayList<String>[3]; // not allowed

List<Integer> listOfInteger = new ArrayList<Integer>();listOfInteger.add(10);listOfInteger.add(20);listOfInteger.add(30);

Object[] arrayOfObject = (Object[]) arrayOfListOfString ;arrayOfObject[0] = listOfInteger;// run-time error: ClassCastExceptionString s = arrayOfListOfString[0].get(2);

}}

11/01/61Page 303

Upper Bounded

public final class PairWithBound<X, Y extends Comparable> {private X first;private Y second;public PairWithBound(X first, Y second) {

this.first = first;this.second = second;

}public X getFirst() { return first; }

public int compares(PairWithBound<X, Y> other) {return this.second.compareTo(other.second);

}}

11/01/61Page 304

Wildcard (1)

import java.util.*;

public class ProcessList {public void print(List<Object> list) {

for (Object o : list)System.out.println(o);

}}

11/01/61Page 305

Wildcard (2)

import java.util.*;

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

List<Integer> list = new ArrayList<Integer>();list.add(10);list.add(20);list.add(30);ProcessList.print(list); // compile fails

}}

11/01/61Page 306

Wildcard (3)

import java.util.*;

public class ProcessList {public static void print(List<?> list) {

for (Object o : list)System.out.println(o);

}}

11/01/61Page 307

Lower Bound

11/01/61Page 308

Generic Method

public class Max {static public <T extends Comparable> T max(T t1, T t2) {

if (t1.compareTo(t2) > 0) {return t1;

return t2;}

}

11/01/61Page 309

Generic Method

public class TestMax {

public static void main(String[] args) {String s = Max.max("somying", "somchai");Integer i = Max.max(10, 20);System.out.println(s);System.out.println(i);

}}

11/01/61Page 310

Wildcard

11/01/61Page 311

Wildcard

• Wildcard– void printElements(List<?> myList) { ... }

• List<?> is the supertype of all kind of List

• Bounded wildcard– void printElements(List<? extends E> myList) { ... } – void printElements(List<? super E> myList) { ... }

11/01/61Page 312

List of Unknown Type

import java.util.*;

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

List<String> listOfString;List<?> listOfUnknown;listOfString = new ArrayList<String>();listOfString.add("hi");listOfUnknown = listOfString;listOfUnknown.add(new Object()); // compile failsObject obj = listOfUnknown.get(0);System.out.println(obj);

}}

11/01/61Page 313

Bounded Wildcard

public void draw(List<Shape> shape) {for(Shape s: shape) { s.draw(this);

} }

public void draw(List<? extends Shape> shape) { // rest of the code is the same

}

ไมสามารถวาดList<Rectangle> ได

11/01/61Page 314

อนเนอรคลาส (inner class)

อ. นฐพงศ สงเนยมhttp://www.siam2dev.comxnattapong@hotmail.com

11/01/61Page 315

หวขอ

• อนเนอรคลาส• ตวอยางการใชงานอนเนอรคลาสเพอจดการกบ

เหตการณ• ประโยชนของ inner class• ประเภทของ inner class

11/01/61Page 316

อนเนอรคลาส

11/01/61Page 317

อนเนอรคลาส

• คลาสทอยภายในคลาสอน• The class that encloses it is called the outer

or top-level class.• มกใชเพอจดการกบเหตการณ (event)

11/01/61Page 318

ตวอยางการใชงานอนเนอรคลาสเพอจดการกบเหตการณ

11/01/61Page 319

เฟรมเปลา

import javax.swing.*;

public class NoButton extends JFrame {public static void main(String[] args) {

JFrame frame = new NoButton();frame.setSize(150, 70);frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);frame.setVisible(true);

} }

11/01/61Page 320

เฟรมเปลา

11/01/61Page 321

เพมป มในเฟรม

import javax.swing.*;import java.awt.*;

public class OneButtonNoHandler extends JFrame {public OneButtonNoHandler() {

button = new JButton("One");add(button);getContentPane().setLayout(new FlowLayout());

}

JButton button;...

}

11/01/61Page 322

เพมป มในเฟรม

11/01/61Page 323

รบรการกดป ม

import javax.swing.*;import java.awt.*;import java.awt.event.*;

public class OneButton extends JFrame implements ActionListener {public OneButton() {

...button.addActionListener(this);

}

public void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(this, "You clicked One.");

}}

11/01/61Page 324

รบรการกดป ม

11/01/61Page 325

มสองป มในเฟรม

public class TwoButtons extends JFrame implements ActionListener {public TwoButtons() {

button1 = new JButton("One");button1.addActionListener(this);

button2 = new JButton("Two");button2.addActionListener(this);

add(button1);add(button2);getContentPane().setLayout(new FlowLayout());

}...

11/01/61Page 326

มสองป มในเฟรม

public class TwoButtons extends JFrame implements ActionListener {public void actionPerformed(ActionEvent e) {

if (e.getSource() == button1) {JOptionPane.showMessageDialog(this, "You clicked One.");

}if (e.getSource() == button2) {

JOptionPane.showMessageDialog(this, "You clicked Two.");}

}...

}

11/01/61Page 327

มสองป มในเฟรม

11/01/61Page 328

ใช inner class

public class TwoButtonsWithMemberClass extends JFrame {class Button1Handler implements ActionListener {

public void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(null, "You clicked One.");

}}class Button2Handler implements ActionListener {

public void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(null, "You clicked Two.");

}}...

11/01/61Page 329

ใช inner class

public class TwoButtonsWithMemberClass extends JFrame {public TwoButtonsWithMemberClass () {

JButton button1 = new JButton("One");button1.addActionListener(new Button1Handler());

JButton button2 = new JButton("Two");button2.addActionListener(new Button2Handler());

add(button1);add(button2);

getContentPane().setLayout(new FlowLayout());}...

11/01/61Page 330

ใช inner class

11/01/61Page 331

ขอดของ inner class

• Organization– Allows us to further organize package structure through

the use of namespaces• เขาใจงาย

– Sometimes a class is only needed by one other class– Sometimes a class needs access to many variables and

methods of another class– Sometimes a class is only needed once, for one object, in

one specific place• ประโยชน

– Handle GUI event– Thread– Timer

11/01/61Page 332

ประเภทของอนเนอรคลาส

11/01/61Page 333

ประเภทของอนเนอรคลาส

• Member classes (ตวอยางทผานมา)• Local classes • Anonymous classes • Static member classes (not a real inner class)

11/01/61Page 334

Member class

class EnclosingClass { class MemberClass {

... } ...

}

11/01/61Page 335

Member class

• defined as a member of a class. • instance specific and has access to any and

all methods and members

11/01/61Page 336

ตวอยาง Member class

public class Stack { private Object[] items; //code for Stack's methods and constructors not shownpublic Iterator iterator() {return new StackIterator(); } class StackIterator implements Iterator {

int currentItem; public boolean hasNext() { ... } public Object next() { ... } public void remove() { ... }

} }

11/01/61Page 337

Local class

class EnclosingClass { public void foo() {

class LocalClass {...

}...

} }

11/01/61Page 338

Local class

• declared within a block of code and are visible only within that block, just as any other method variable.

• The object in this class cannot access local variable– Can access final variable

11/01/61Page 339

Local inner class

public class TwoButtonsWithInnerClass extends JFrame {public TwoButtonsWithLocalClass() {

class Button1Handler implements ActionListener {public void actionPerformed(ActionEvent e) {

JOptionPane.showMessageDialog(null, "You clicked One.");}

}class Button2Handler implements ActionListener {

public void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(null, "You clicked Two.");

}}JButton button1 = new JButton("One");button1.addActionListener(new Button1Handler());

11/01/61Page 340

Anonymous inner class

class EnclosingClass { public void foo() {

someMethod(new SomeInterfaceOrClass() {public void implementedMethod() {

... }

});...

} }

11/01/61Page 341

Anonymous Inner Class

• a local class that has no name • must always extend a super class or implement an

interface but it cannot have an explicit extends or implements clause

• must implement all the abstract methods in the super class or the interface.

• always uses the default constructor from the super class to create an instance

11/01/61Page 342

ตวอยาง Anonymous inner class

public class TwoButtonsWithInnerClass extends JFrame {public TwoButtonsWithInnerClass() {

JButton button1 = new JButton("One");button1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(null, "You clicked One.");

}});JButton button2 = new JButton("Two");button2.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {JOptionPane.showMessageDialog(null, "You clicked Two.");

}});

11/01/61Page 343

Static inner class

class EnclosingClass { static class StaticNestedClass {

... } ...

}

11/01/61Page 344

Static inner class

• has access to all static methods of the parent, or top-level, class.

• cannot access instance variables of its enclosing class.

11/01/61Page 345

Unit Test

11/01/61Page 346

Unit Test

• Test เพอแสดงวามบกในโปรแกรม• Debug เพอแกบก• Unit Test

– ทดสอบความถกตองของคลาส– ชวยใหเรามนใจในคณภาพของซอฟทแวรและลดเวลาใน

การพฒนาซอฟทแวรลงไป – ชวยตรวจสอบเมอมการเปลยนแปลง (refactor)– JUnit

11/01/61Page 347

XP (eXtreme Programming)

• Code the unit test first • ทาใหโปรแกรมเมอร

– ทราบวาตองเขยนอะไรบาง– รวาทางานเสรจเมอไร – พบปญหาเรวขน– บงคบใหตองออกแบบคลาสเพอใหตรวจสอบไดงาย– เขยนโคดใหพอทจะผานการทดสอบ– คนอนทราบวาคลาสของเราใชงานอยางไร (ดจาก Test

Code)

11/01/61Page 348

คณสมบตของการทดสอบ

• การทดสอบควรทาโดยอตโนมต– ไมใชพมพอนพตทางคยบอรด กดป ม และดผลเอง

• ตวทดสอบตองทราบผลการทางานทถกตอง

11/01/61Page 349

ความเชอ

• ทดสอบเพอแสดงใหเหนวาโปรแกรมทเราเขยนขนนนถกตอง– I get into the meanest, nastiest frame of mind that I can

manage, and I write the nastiest [testing] code I can think of; then I turn around and embed that in even nastier constructions that are almost obscene. - Knuth

• คลาสทผานการทดสอบแลวไมมขอผดพลาด– Testing can only prove the presence of bugs, not their

absence. -Dijkstra

• การทดสอบทาใหรจดทผดพลาดของโปรแกรม– Testing is not debugging

11/01/61Page 350

JUnit

• A simple framework to write repeatable tests • Features

– Assertions for testing expected results – Test fixtures for sharing common test data – Test suites for easily organizing and running tests – Graphical and textual test runners

• http://www.junit.org/

11/01/61Page 351

คลาสทจะทดสอบpublic class Rank {

public int a, b, c;public Rank(int a, int b, int c) {

this.a = a;this.b = b; this.c = c;

}public int go() {

if (a > b && a > c) return 1;

if (b > a && b > c) return 2;

return 3;}

}

เมธอด go() คนคาเปนตวเลข•ถา a มากทสด คนคา 1•ถา b มากทสด คนคา 2•ถา c มากทสด คนคา 3•ถามตวทเทากน คนคาเปนหมายเลขของตวแปรตวแรกทมากสด

11/01/61Page 352

NetBeans: ทดสอบคลาส Rank

• ไปท Projects– คลกขวาทซอรสไฟล>Tools>Create JUnit Test– หรอ กด Ctrl+Shift+U

• ทเมธอด testGo()– ลบ fail() ทง– เขยน test case

11/01/61Page 353

assertEquals(expectedResult, actualResult)

public void testGo() {System.out.println("go");

Rank instance = new Rank(1,2,3);

int expResult = 3;int result = instance.go();assertEquals(expResult, result);

}

• Test cases– ((1,2,3),3)– ((1,3,2),2)– ((3,1,2),1)

11/01/61Page 354

ทดสอบทกครงหลงเปลยนแปลง

• เปลยนชอตวแปร a เปน aaaaaaaaaa• ทดสอบใหม

11/01/61Page 355

setUp()public class RankTest extends TestCase {

Rank rank;

protected void setUp() throws Exception {rank = new Rank(0,0,0);

}

public void testGo1() {rank.b = 2;assertEquals(2,rank.go());

}public void testGo2() {

rank.c = 1;assertEquals(3,rank.go());

}...

}

11/01/61Page 356

Test a Method that Returns Nothing

• เมธอดทเปน void ไมคนคา• เรยกเมธอดอนเพอตรวจสอบผลขางเคยงของการ

เรยกเมธอดทไมคนคา

11/01/61Page 357

ทดสอบเมธอด setCharAt() ของคลาส StringBuilder

import junit.framework.*;

public class StringBuilderTest extends TestCase{public void testSetCharAt(){

StringBuilder sb = new StringBuilder("Tsubasa");char c = 'Z';sb.setCharAt(0,c);assertTrue(sb.charAt(0) == c);

}}

11/01/61Page 358

Failure

11/01/61Page 359

Failure

public void testEquals3() {System.out.println("testEquals3");AddOne b = new AddOne(20);assertEquals(21,b);

}

11/01/61Page 360

ผลการทดสอบ

Testsuite: AddOneTestTests run: 4, Failures: 1, Errors: 0, Time elapsed: 0.01 sec

------------- Standard Output ---------------testInctestEquals1testEquals2testEquals3------------- ---------------- ---------------

11/01/61Page 361

ผลการทดสอบ

Testcase: testEquals3(AddOneTest): FAILEDexpected:<21> but was:<20>junit.framework.AssertionFailedError: expected:<21> but was:<20>

at AddOneTest.testEquals3(AddOneTest.java:43)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

11/01/61Page 362

Error

11/01/61Page 363

Error

• หมายถงTestsuite: AddOneTestTests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.01 sec

• เกดขนในกรณทเกด exception แตไมถก catch• ไมไดเปนการบอกวาเราเขยนโปรแกรมผดพลาด• คนละความหมายกบการ throw Error ทวไป

– ปรกต JVM จะ throw Error ในกรณทเกดปญหาในระดบลางซงไมสามารถแกไขได เชน โหลดคลาสไมได

11/01/61Page 364

ทดสอบการ throw Exception

import junit.framework.*;

public class ThrowerTest extends TestCase {public void testThrow() throws Exception {

System.out.println("testThrow");try{

Thrower.throw();fail("exception should be thrown");

} catch(IllegalArgumentException e) {}}

}

11/01/61Page 365

ทดลอง throw Exception ตามทตวทดสอบคาดไว

public class Thrower {public static void throw() {

throw new IllegalArgumentException();}

}

11/01/61Page 366

ผลการทดลอง throw Exceptionตามทตวทดสอบคาดไว

Testsuite: ThrowerTestTests run: 1, Failures: 0, Errors: 0, Time elapsed: 0.01 sec

------------- Standard Output ---------------testThrow------------- ---------------- ---------------

11/01/61Page 367

ทดลอง throw ผดประเภท

public class Thrower {

public static void throw() {throw new NullPointerException();

}}

11/01/61Page 368

ผลการทดลอง throw ผดประเภท

Testsuite: ThrowerTestTests run: 1, Failures: 0, Errors: 1, Time elapsed: 0.01 sec

------------- Standard Output ---------------testThrow------------- ---------------- ---------------Testcase: testThrow(ThrowerTest): Caused an ERRORnulljava.lang.NullPointerException

at Thrower.throw(Thrower.java:4)at ThrowerTest.testThrow(ThrowerTest.java:7)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

11/01/61Page 369

ทดลองไม throw

public class Thrower {public static void throw() {}

}

11/01/61Page 370

ผลการทดลองไม throw

Testsuite: ThrowerTestTests run: 1, Failures: 1, Errors: 0, Time elapsed: 0.01 sec

------------- Standard Output ---------------testThrow------------- ---------------- ---------------Testcase: testThrow(ThrowerTest): FAILEDexception should be thrownjunit.framework.AssertionFailedError: exception should be thrown

at ThrowerTest.testThrow(ThrowerTest.java:8)at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)

11/01/61Page 371

โจทยคลาส

11/01/61Page 372

1. คลาส Counter

• เมธอด– void up()

• นบขน

– int getNumber()• คนคาทนบได

• ทดสอบดวย JUnit

• แสดงตวอยาง GUI

11/01/61Page 373

2. class TrafficLight

• เมธอด– String getColor()

• คนคาสของไฟจราจรขณะนน

– void next()

• GUI

11/01/61Page 374

3. class Person

• แอตทรบวต– String name– double salary

• คอนสตรกเตอร– Person(String n, double salary)

• เมธอด– void setSalary(double s)– boolean hasHigherSalary(Person other)– void increaseSalary(int percent)

11/01/61Page 375

ตวอยาง GUI

11/01/61Page 376

4. class BankAccount• เมธอด

– void deposit(double amount)– void withdraw(double amount)– void transfer(BankAccount, double

amount)– double getBalance()

• ทดสอบการทางาน

11/01/61Page 377

ฝากถอนดวย BankAccount

11/01/61Page 378

โอนเงนดวย BankAccount

11/01/61Page 379

5. class BankAccount with Exception

• แกไขคลาส BankAccount – void deposit(double amount)

• ให throw new IllegalArgumentException() เมอamount นอยกวาหรอเทากบ 0

– void withdraw(double amount)• ให throw new Exception() เมอ amount นอยกวา

หรอเทากบ 0– void transfer(BankAccount, double

amount)– double getBalance()

Presenter
Presentation Notes
unit test error

11/01/61Page 380

โจทย enum

11/01/61Page 381

Position

• PROFESSOR, ASSOCIATE_PROFESSOR, ASSISTANT_PROFESSOR, LECTURER

• boolean higher(enum Position)

11/01/61Page 382

ทดสอบอนม Position

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

Position p = Position.PROFESSOR;Position q = Position.ASSISTANT_PROFESSOR;Position r = Position.LECTURER;System.out.println(p.isHigher(q));System.out.println(q.isHigher(p));System.out.println(q.isHigher(r));

}}

11/01/61Page 383

โจทย interface

11/01/61Page 384

class Person implements Comparator

• เปรยบเทยบตาแหนงกอน ถาตาแหนงเทากน ให เทยบเงนเดอน

• ตาแหนง– enum Position

11/01/61Page 385

โจทยแพคเกจ

11/01/61Page 386

HelloWorld

• ใช NetBeans สรางคลาส HelloWorld ในแพคเกจhello

• ไปท command prompt และลองรน

11/01/61Page 387

Counter

• เขยนคลาส Counter ในแพคเกจ somchai• เขยนคลาสเฟรมในแพคเกจ somying

– คลาสเฟรมใช Counter