A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 赵燕燕 黑马帝   /  2011-11-16 19:10  /  1743 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 赵燕燕 于 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;
                                         ;

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

5 个回复

倒序浏览
你理解错误了,本应该就是向下转换,如果传的是动物型 ,则不能转换在BaseStudent,所以if不会执行,你要转过来这个湾。
                if(!(obj instanceof BaseStudent))     
                         BaseStudent b=(BaseStudent)obj;
                 return b==this;     
你这写相当于把b写成if语句内的变量,要写在外边

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

回复 使用道具 举报
                  if(obj instanceof BaseStudent)     
                  {
          BaseStudent b=(BaseStudent)obj;
                   return b==this;
          }               
              else return false;
改成这样就可以了

点评

这样解释还比较合理  发表于 2011-11-17 06:49

评分

参与人数 1技术分 +1 收起 理由
admin + 1

查看全部评分

回复 使用道具 举报
把非去掉  instanceof是判断类型的  应该是是这个类性的时候进行转换
回复 使用道具 举报
谢谢啊,只有改成这样才行  if(obj instanceof BaseStudent)     
                  {
          BaseStudent b=(BaseStudent)obj;
                   return b==this;
          }               
              else return false;

可惜的是,传入动物类时,返回的也是false不能给出相应提示
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马