Computer >> Máy Tính >  >> Lập trình >> Java

Làm thế nào để truy cập một biến thành viên lớp dẫn xuất bởi một đối tượng giao diện trong Java?

Khi bạn cố gắng giữ biến tham chiếu của lớp siêu với một đối tượng lớp con, bằng cách sử dụng đối tượng này, bạn chỉ có thể truy cập vào các thành viên của lớp siêu, nếu bạn cố gắng truy cập các thành viên của lớp dẫn xuất bằng cách sử dụng tham chiếu này, bạn sẽ nhận được thời gian biên dịch lỗi.

Ví dụ

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();
   }
}

Đầu ra

InterfaceExample.java:14: error: cannot find symbol
      obj.display();
          ^
   symbol: method display()
   location: variable obj of type Sample
1 error

Nếu bạn cần truy cập các thành viên lớp dẫn xuất với tham chiếu của siêu lớp, bạn cần truyền tham chiếu bằng toán tử tham chiếu.

Ví dụ

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();
   }
}

Đầu ra

This is demo method-1
This is a method of the sub class