定义两个类Person,Student. Student是Person的子类
Student中有一个方法 void geta();Person p=new Person();为什么这样可以: (Student)p.geta();而这样不可以? :
p=(Student)p;
p.geta();
Student中有一个方法 void geta();Person p=new Person();为什么这样可以: (Student)p.geta();而这样不可以? :
p=(Student)p;
p.geta();
为什么这样可以: (Student)p.geta(); //你确信这样能行?应该出问题Person p=new Student();
(Student)p.geta(); //这样才可以p是Person类型的变量,但是指向Student实例,所以(Student)p这样向下转换没问题,即相当于某个临时变量 Student s = (Student)p; 然后通过临时变量调用 s.geta();p=(Student)p; //这个p还是Person类型的变量,注意这里和上面的临时变量的区别
p.geta(); //所以编译期间编译器不能知道p有geta方法,所以编译没法通过
private EntityID getEntrance(EntityID b){
StandardEntity e=this.model.getEntity(b);
if(e instanceof Building){
List<Edge> edges=((Building)e).getEdges();
for(Edge e1:edges){
if(e1.isPassable()){
EntityID temp=e1.getNeighbour();
return temp;
}
}
return null;
}
else return null;
}
StandardEntity e=this.model.getEntity(b);
if(e instanceof Building){
List<Edge> edges=((Building)e).getEdges(); //这行有问题
for(Edge e1:edges){
if(e1.isPassable()){
EntityID temp=e1.getNeighbour();
return temp;
}
}
return null;
}
else return null;
}这样是对的。
如果变成e=(Building)e
List<Edge> edges=e.getEdges();
就编译出错。错误原因:The method getEdges() is undefined for the type StandardEntity
Person p=new Person();为什么这样可以: (Student)p.geta(); //貌似编译错误。正确的形式是: Person p = new Student(); p.geta();
p=(Student)p;
p.geta(); // 父类 = 子类 子类 = (子类)父类
// 类型转换之前 - 明确确定其具体指向
// 这样,我打个比方: 学生是人吧,但人一定是学生么?
LZ何必把人强制转换为学生呢?
我贴出来的源代码,可以看出来,传过来的对象是一个父类对象 StandardEntity。想用到子类对象getEdges的方法,因为父类里面没有getEdges(),需要转型是吧。然后我就这样做了/
我就想问:
e=(Building)e
List<Edge> edges=e.getEdges();
和
List<Edge> edges=((Building)e).getEdges();
有什么区别?
为什么一个对,一个不对?
谢谢大家了。