fhhandcc
fhhandcc
采纳率100%
2015-10-24 08:42

菜鸟求助子类toString()重写

已采纳

class Person {
String name;
String location;

Person(String name) {
    this.name = name;
    location = "beijing";
}

Person(String name,String location) {
    this.name = name;
    this.location = location;   
}

public String info() {
    return 
    "name:"+name+
    "location:"+location;
}

public String toString() {
    return "I'm a human!";
}

public boolean equals(Object obj) {
    if(obj == null) return false;
    else{
        if(obj instanceof Person) {
            Person p = (Person)obj;
            if(p.name == this.name && p.location == this.location) {
                return true;
            }
        }
    }

    return false;
}

}

class Student extends Person {
String school;

Student(String name,String school) {
    this(name,school,"Xi'an");
}

Student(String n,String s,String l) {
    super(n,l);
    this.school = s;
}

public String info() {
    return super.info()+"school:"+school;
}   

public String toString {
    return "I'm a studet.";
}
public boolean equals(Object obj) {
    if(obj == null) return false;
    else{
        if(obj instanceof Student){
            Student s = (Student)obj;
            if(s.name == this.name&&s.location == this.location&&s.school == this.school) {
                return true;
            }
        }
    }
    return false;   
}

}

public class TestTSandEQ {
public static void main(String[] arg) {
Person p1 = new Person("A","beijing");
Person p2 = new Person("B","beijing");
Student s1 = new Student("A","XD","beijing");
Student s2 = new Student("B","XD");

    System.out.println(p1.info());
    System.out.println(p2.info());
    System.out.println(s1.info());
    System.out.println(s2.info());
    System.out.println("p1:"+p1.toString());
    System.out.println("s1:"+s1.toString());
}

}
Student类中toString()一直提示少一个;图片说明 目前用ultraedit

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • u011596810 「已注销」 6年前

    public String toString {
        return "I'm a studet.";
    }
    
    

    变为

    public String toString() {
        return "I'm a studet.";
    }
    
    
    点赞 评论 复制链接分享
  • u012263331 myleo_lost-a-horse 6年前

    public String toString {
    return "I'm a studet.";
    }
    很明显漏了一对括号()

    public String toString() {
    return "I'm a studet.";
    }

    点赞 评论 复制链接分享

相关推荐