การโปรแกรมเชิงวัตถุ (Object-Oriented Programming)
แนวคิดของการโปรแกรมเชิงวัตถุ (OOP Concepts) 1) การปกป้อง (Encapsulation) คือ การรวมกลุ่มของข้อมูล และกลุ่มของโปรแกรม เพื่อการปกป้อง และเลือกตอบสนอง 2) การสืบทอด (Inheritance) คือ ยอมให้นำไปใช้ หรือเขียนขึ้นมาทดแทนของเดิม 3) การพ้องรูป (Polymorphism) มี 2 แนวคิดประกอบด้วย Overloading มีชื่อโปรแกรมเดียวกัน แต่รายการตัวแปร (Parameter List) ต่างกัน และ Overriding มีชื่อโปรแกรม และตัวแปรเหมือนกัน เพื่อเขียน behavior ขึ้นมาใหม่
1 คอนสตักเตอร์ (Constructor)
ตัวอย่าง 8.1 ทดสอบ
class father {
father() { System.out.println(5); }
}
2 การปกป้อง (Encapsulation)
ตัวอย่าง 8.2 ทดสอบ
class father {
int n_time;
private int to_show (int run_time) {
run_time = n_time + 1;
return run_time;
}
}
3 การสืบทอด (Inheritance)
การสืบทอด (Inheritance) คือ การขอใช้คุณสมบัติ หรือวัตถุของซุปเปอร์คลาส (Super Class) ได้ทันที ถ้าซับคลาส (Sub Class) ต้องการเขียนขึ้นใหม่โดยใช้ชื่อ และแอททริบริ้ว (Attribute) เดิม ก็สามารถทำได้เช่นกัน
ซุปเปอร์คลาส (Super Class) คือ คลาสที่ถูกสืบทอดคุณสมบัติไปใช้ในคลาสที่สร้างขึ้นใหม่ภายหลัง
ซับคลาส (Sub Class) คือ คลาสที่ไปสืบทอดคุณสมบัติของคลาสที่สร้างขึ้นใหม่ก่อนหน้านี้
ตัวอย่าง 8.3 ทดสอบ
class child extends father {
child() {
n_time = 5;
System.out.println(to_show(n_time)); // 7
}
public static void main(String[] a) {
new child();
}
private int to_show (int run_time) {
run_time = n_time + 2;
return run_time;
}
}
4 การพ้องรูป (Polymorphism)
โอเวอร์ไรดิ้ง (Overriding) คือ การเขียนเมธอดที่มีชื่อเหมือนกับเมธอดในซุปเปอร์คลาส (Super Class) ทุกอย่างรวมทั้งแอททริบริ้ว (Attribute)
ตัวอย่าง 8.4 ทดสอบ
class child extends father {
public static void main(String[] a) {
new child();
}
private int to_show (int run_time) {
run_time = n_time + 2;
return run_time;
}
}