本帖最后由 赵燕燕 于 2011-11-23 11:30 编辑
class Student
{
private int x;
public void setX(int x)
{
this.x=x;
}
/*
public String toString()
{
return "x=="+x;
}
*/
}
class BaseStudent extends Student
{
public boolean equals(Object obj)
{
if(!(obj instanceof BaseStudent))
BaseStudent b=(BaseStudent)obj;
return b==this;
}
}
class StudentDemo
{
public static void main(String[] args)
{
BaseStudent s1=new BaseStudent();
BaseStudent s2=new BaseStudent();
System.out.println(s1.equals(s2));
}
}
1.上面的equals()方法中, 为什么是 !(obj instanceof BaseStudent) 时进行向下转换,如果传入的参数是指向动物类型的,此时符合if条件,难道还要进行向下转换吗?
2.编译时会提示:
错误:不是语句 BaseStudent b=(BaseStudent)obj;
^
错误: 需要 ';' BaseStudent b=(BaseStudent)obj;
; |