1. 976-140 Object-Oriented Programming
344-202 Introduction to OOP
การโปรแกรมเชิงวัตถุ
8. Inheritance
Faculty of Technology and Environment
Prince of Songkla University, Phuket Campus
2/2551
2. Why inheritance?
How to programming for all characters in the game?
Object-Oriented Programming 2/2551 2
3. Why inheritance?
Student GradStudent Staff Lecturer
Id Id Id Id
Name Name Name Name
Major Major Office Office
register() thesis Salary Salary
checkGrade() register() paySalary() assignCourse()
checkActivity() checkGrade() checkDayOff() paySalary()
listConference() checkDayOff()
Reus
e
Object-Oriented Programming 2/2551 3
5. "is a" versus "has a" Relationships
ความสัมพันธ์ระหว่างคลาส 2 แบบ ได้แก่
ความสัมพันธ์แบบ is a : การสืบทอดคลาส (Inheritance)
• คลาสแรกเป็น subclass ของคลาสที่สอง
a car is a vehicle
ความสัมพันธ์แบบ has a : การประกอบคลาส (Composition)
• คลาสแรกมีคลาสที่สองเป็น attribute
a car has wheels
Object-Oriented Programming 2/2551 5
6. Composition
การประกอบคลาส เป็นการนาคลาสที่มอยู่มาประกอบเป็นคลาสใหม่
ี
Example:
public class Address {
String number;
String road;
String city;
String province;
String postcode;
}
public class Person {
String name;
String birthDate;
Address address;
}
Object-Oriented Programming 2/2551 6
8. Inheritance – class diagram
A เป็นคลาสแม่ของ B นั่นคือ B สืบทอดคุณสมบัตมาจาก A
ิ
A
คลาสแม่
Vehicle สัญลักษณ์ลูกศรแสดงการสืบทอด
Bก
คลาสลู
Helicopter Bicycle Car
Racing Sedan
Object-Oriented Programming 2/2551 8
33. Keyword final
Final class : ถ้า class ใดประกาศให้เป็น final จะไม่สามารถนามาสืบทอด
ได้อีก
Compile error!!!
InheritanceDemo1.java:12:
cannot inherit from final
Employee
Object-Oriented Programming 2/2551 33
34. Keyword final
Final method: ถ้าเมธอดใดเป็น final จะไม่สามารถนามา override ได้อีก
Compile error!!!
InheritanceDemo1.java:14:
printData() in Manager cannot
override printData() in Employee;
overridden method is final
Object-Oriented Programming 2/2551 34