java 继承 instanceof 问题

lvjun106 2007-11-01 11:46:43
class Inter{
int a=10;
}
public class Test extends Inter{
int c=8;
public int getC(){
return c;
}
public static void main(String args[]){
Inter b=new Inter();
b=new Test();
if(b instanceof Test){
System.out.print("ok!");
//System.out.print(c.getC());为什么这句不能实现?
}
if(b instanceof Inter){
System.out.print("super is also ok!");
}
}
}
...全文
47 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
lvjun106 2007-11-14
  • 打赏
  • 举报
回复
THANK YOU!
I mistake the "b=new Test()";
z_lping 2007-11-01
  • 打赏
  • 举报
回复
This is nothing to do with "instanceof" operator.

Reference Variable "b" is of type "Inter". b.getC() fails because there is no method called "getC()" defined in class Inter. To make it work, you have to cast b to type "Test".


if (b instanceof Test) {
System.out.println("OK!");
System.out.println(((Test)b).getC());
}


62,616

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧