如何在 Java 中通过接口对象访问派生类成员变量?
javaobject oriented programmingprogramming更新于 2024/2/18 10:20:17
当您尝试使用子类对象保存超类的引用变量时,使用此对象您只能访问超类的成员,如果您尝试使用此引用访问派生类的成员,您将收到编译时错误。
示例
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
如果您需要使用超类的引用访问派生类成员,则需要使用引用运算符强制转换引用。
示例
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
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

