Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ความแตกต่างระหว่าง super() และ this() ใน Java

Java มีคีย์เวิร์ดพิเศษ this และ super ใช้แทน instance ปัจจุบันของคลาส และ superclass ตามลำดับ ทั้งคู่มีความแตกต่างสำคัญดังตาราง:

ลำดับ หัวข้อ this super
1 Represent และ Reference this แทน instance ปัจจุบันของคลาส super แทน instance ปัจจุบันของ parent class
2 Interaction with Constructor this() เรียก default constructor ของคลาสเดียวกัน super() เรียก default constructor ของ parent class
3 Method Accessibility this เรียก method ของคลาสปัจจุบัน super เรียก method ของ parent class
4 Static Context this เรียกจาก static context ได้ (เช่น System.out.println(this.x) ได้) super เรียกจาก static context ไม่ได้ (System.out.println(super.x) compile error)

ตัวอย่าง this vs super

class A {
    public int x, y;
    public A(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

class B extends A {
    public int x, y;
    public B() {
        this(0, 0);
    }
    public B(int x, int y) {
        super(x + 1, y + 1);  // เรียก parent constructor
        this.x = x;
        this.y = y;
    }
    public void print() {
        System.out.println("Base class : {" + x + ", " + y + "}");
        System.out.println("Super class : {" + super.x + ", " + super.y + "}");
    }
}

class Point {
    public static void main(String[] args) {
        B obj = new B();
        obj.print();
        obj = new B(1, 2);
        obj.print();
    }
}

ผลลัพธ์

Base class : {0, 0}
Super class : {1, 1}
Base class : {1, 2}
Super class : {2, 3}