แต่พอมี super แล้วก็มักมีคำว่า this ประกบ ซึ่งความหมายที่ต่างกันคือ
super = การอ้างอิงไปหาสมาชิกของ class แม่
this = การอ้างอิงไปหาสมาชิกของตนเอง
สมมุติว่าเรามีโค้ดแบบนี้
package myPackage; class A1 { int x = 1; }
class A2 extends A1 { int x = 2; void print() { System.out.println(this.x + ", " + super.x); } }
public class SuperTest { public static void main(String[] args) { new A2().print(); } }
ผลการทำงาน
2, 1
อธิบาย
ตัวอย่างนี้ คลาส A1 มี x ซึ่งมีค่าเป็น 1 ส่วน A2 ก็มี x ที่มีค่าเป็น 2 พอเราต้องการอ้างอิงตัวแปร x ของ A2 เราก็ใช้ this.x ส่วนเมื่อเราต้องการอ้างอิงค่า x ของ class แม่ เราก็ใช้ super.x
1 ความคิดเห็น:
ship nhanh đi Malawi
ship chứng từ đi Ecuador
chuyển phát cấp tốc tới Georgia
แสดงความคิดเห็น