如何通过Java中的接口对象访问派生的类成员变量?
当您尝试通过子类对象保留超类的引用变量时,使用该对象只能访问超类的成员,如果尝试使用此引用访问派生类的成员,则会获得编译时错误。
示例
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
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短