Kế thừa là quan hệ giữa hai class, một class kế thừa thuộc tính class kia. Dùng extends:
public class A extends B { }
Class kế thừa = sub/child class, class được kế thừa = super/parent class. Bản sao thành viên super class tạo trong sub class object → dùng sub class object truy cập cả hai.
Chuyển đổi sub class variable thành super class type
Có thể gán trực tiếp sub class variable vào super variable. Tóm lại: super class reference variable CÓ THỂ giữ sub class object. Nhưng dùng reference này chỉ truy cập được member của super class, nếu truy cập sub class member → compile error.
Ví dụ 1
class Person {
public String name;
public int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public void displayPerson() {
System.out.println("Data of the Person class: ");
System.out.println("Name: " + this.name);
System.out.println("Age: " + this.age);
}
}
public class Sample extends Person {
public String branch;
public int Student_id;
public Sample(String name, int age, String branch, int Student_id) {
super(name, age);
this.branch = branch;
this.Student_id = Student_id;
}
public void displayStudent() {
System.out.println("Data of the Student class: ");
System.out.println("Name: " + super.name);
System.out.println("Age: " + super.age);
System.out.println("Branch: " + this.branch);
System.out.println("Student ID: " + this.Student_id);
}
public static void main(String[] args) {
Person person = new Person("Krishna", 20);
Sample sample = new Sample("Krishna", 20, "IT", 1256);
person = sample; // Upcasting
person.displayPerson();
}
}
Đầu ra
Data of the Person class: Name: Krishna Age: 20
Ví dụ 2
class Super {
public Super() {
System.out.println("Constructor of the Super class");
}
public void superMethod() {
System.out.println("Method of the super class ");
}
}
public class Test extends Super {
public Test() {
System.out.println("Constructor of the sub class");
}
public void subMethod() {
System.out.println("Method of the sub class ");
}
public static void main(String[] args) {
Super obj = new Test(); // Upcasting
obj.superMethod();
}
}
Đầu ra
Constructor of the Super class Constructor of the sub class Method of the super class