程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> 對象-菜鳥求助子類toString()重寫

對象-菜鳥求助子類toString()重寫

編輯:編程綜合問答
菜鳥求助子類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

最佳回答:


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

變為

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved