เมื่อคุณพยายามเก็บตัวแปรอ้างอิงของ super class ด้วยวัตถุ sub class โดยใช้วัตถุนี้ คุณสามารถเข้าถึงสมาชิกของ super class ได้เท่านั้น หากคุณพยายามเข้าถึงสมาชิกของคลาสที่ได้รับโดยใช้การอ้างอิงนี้ คุณจะได้รับเวลาในการรวบรวม ผิดพลาด
ตัวอย่าง
interface Sample {
void demoMethod1();
}
public class InterfaceExample implements Sample {
public void display() {
System.out.println("This ia a method of the sub class");
}
public void demoMethod1() {
System.out.println("This is demo method-1");
}
public static void main(String args[]) {
Sample obj = new InterfaceExample();
obj.demoMethod1();
obj.display();
}
} ผลลัพธ์
InterfaceExample.java:14: error: cannot find symbol obj.display(); ^ symbol: method display() location: variable obj of type Sample 1 error
หากคุณต้องการเข้าถึงสมาชิกของคลาสที่ได้รับด้วยการอ้างอิงของ super class คุณจะต้องส่งการอ้างอิงโดยใช้ตัวดำเนินการอ้างอิง
ตัวอย่าง
interface Sample {
void demoMethod1();
}
public class InterfaceExample implements Sample{
public void display() {
System.out.println("This is a method of the sub class");
}
public void demoMethod1() {
System.out.println("This is demo method-1");
}
public static void main(String args[]) {
Sample obj = new InterfaceExample();
obj.demoMethod1();
((InterfaceExample) obj).display();
}
} ผลลัพธ์
This is demo method-1 This is a method of the sub class