Content text ĐA HÌNH - TRỰU TƯỢNG.pdf
Become A Better Developer 28TECH 1 28tech.com.vn ĐA HÌNH VÀ TRỪU TƯỢNG
Become A Better Developer 28TECH 28tech.com.vn 2 1. Đa hình: Đa hình - Polymorphism là một trong 3 tính chất quan trọng của lập trình hướng đối tượng (bên cạnh Đóng gói - Encapsulation và Kế thừa - Inheritance). Đa hình cho phép bạn tham chiếu một biến thuộc kiểu dữ liệu của lớp cơ sở tới đối tượng của một lớp con. Reference variable of parent class Object of Child class Ví dụ: Lớp Student kế thừa từ lớp Person thì tất cả các thực thể (instance) của lớp Student đều là thực thể của lớp Person, nhưng ngược lại thì không.
Become A Better Developer 28TECH 28tech.com.vn 3 1. Đa hình: public class Person { public void display(){ System.out.println("Person !"); } } public class Student extends Person{ public void display(){ System.out.println("Student !"); } } public class Staff extends Person { public void display(){ System.out.println("Staff !"); } } Ví dụ: Kế thừa lớp Person và nạp chồng phương thức display() public class Lecturer extends Person { public void display(){ System.out.println("Lecturer !"); } } public class Main { public static void main(String[] args) { Person p1 = new Student(); Person p2 = new Staff(); Person p3 = new Lecturer(); p1.display(); p2.display(); p3.display(); } } OUTPUT Student ! Staff ! Lecturer !
Become A Better Developer 28TECH 28tech.com.vn 4 2. Dynamic Binding: Trong kế thừa nhiều mức (Multilevel Inheritance) một phương thức có thể được ghi đè ở nhiều lớp trong chuỗi kế thừa, máy ảo Java (JVM) sẽ quyết định phương thức nào được gọi lúc Runtime. public class Person { public void display(){ System.out.println("Person !"); } } public class Student extends Person{ public void display(){ System.out.println("Student !"); } } public class Pupil extends Student{ public void display(){ System.out.println("Pupil !"); } } public class Main { public static void main(String[] args) { Person p1 = new Person(); Person p2 = new Student(); Person p3 = new Pupil(); p1.display(); p2.display(); p3.display(); } } OUTPUT Person ! Student ! Pupil !
Become A Better Developer 28TECH 28tech.com.vn 5 3. Ép kiểu đối tượng và toán tử instanceof: Một biến tham chiếu của đối tượng có thể được ép sang tham chiếu của một đối tượng thuộc lớp khác, đây được gọi là ép kiểu đối tượng public class Main { public static void main(String[] args) { Object ob = new Student(); //Implicit casting Student s = (Student)ob; // Explicit casting } } Implicit casting và Explicit casting