使用toString()方法练习

时间:2018-02-11 06:27:45

标签: java tostring

我是Java的新手,我有一个可能很简单的问题。

我有这段代码:

public class Person {
    String name;
    int age;
    boolean isMan;

    Person(String nameParam,int ageParam,boolean isManParam) {
        this.name = nameParam;
        this.age = ageParam;
        this.isMan = isManParam;
    }
}

在另一个demoClass中,我初始化了类Person的对象:

public class toStringDemo {
    public static void main(String[] args) {
       Person human = new Person("Jack",28,true);
    }
}

我有一个任务是使用toString()方法编写方法showPersonInfo() 显示初始化对象的所有三个字段。任何帮助?

3 个答案:

答案 0 :(得分:2)

每个Java类始终存在toString方法。但是如果你没有覆盖它来指定要返回的内容,它将默认返回" 类名,然后是'at'符号,最后是hashCode ",类似于Person@19821f。更多信息here

所以你应该覆盖toString这样的Person方法(确实改变结果String):

@Override
public String toString() {
      String s = name +", age "+age+", isMan: "+isMan;
      return s;
}

然后要显示此内容,请创建showPersonInfo方法:

public void showPersonInfo(){

   System.out.println(this.toString()); // OR
   // System.out.println(this); // Java prints the toString method by default

}

答案 1 :(得分:0)

public class Person {

String name;
int age;
boolean isMan;


Person(String nameParam,int ageParam,boolean isManParam){
    this.name = nameParam;
    this.age = ageParam;
    this.isMan = isManParam;
     }
}

@Override
public String toString() {
    return "name:" + this.name + ", age:" + this.age + ", isMan:" + this.isMan ;
}

public void showPersonInfo {
    System.out.println(toString());
}

答案 2 :(得分:0)

public class Person {
    String name;
    int age;
    boolean isMan;

    Person(String nameParam,int ageParam,boolean isManParam) {
        this.name = nameParam;
        this.age = ageParam;
        this.isMan = isManParam;
    }

    @Override
    public String toString() {
        return "Name: " + this.name +
               "\nAge: " + this.age +
               "\nIs a Man?: " + this.isMan;
    }

    public String showPersonInfo() {
        return this.toString();
    }
}

在您的主要方法中:

public class toStringDemo {
    public static void main(String[] args) {
        Person human = new Person("Jack",28,true);

        System.out.println(human.showPersonInfo());
    }
}