获取/设置方法输出错误

时间:2013-11-08 10:57:48

标签: java

使用一个小应用程序,允许DVD和主角actor对象显示两个不同的类,但我得到以下输出。

person.Person@10ed7f5c

任何人都可以提供任何有关我出错的信息吗?

DVD类

public class DVD {

private String title;
private Person leadActor;
private int noOfStars;


public DVD (String a,Person person, int b) {

title = a;
leadActor = person;
noOfStars = b;   

}    

public String getTitle(){

return title;

}

public void setTitle(String title){

this.title = title;    
}

public Person getLeadActor(){

return leadActor;
}

public void setLeadActor(Person leadActor){

this.leadActor = leadActor;
}

public int getNoOfStars(){

return noOfStars;
}

public void setNoOfStarts(int noOfStars){

this.noOfStars = noOfStars;

}

@Override
public String toString() {

String s = "Title " + title + "/r" + "Actor:" + leadActor + "/r" + noOfStars;

return s;
}

}

人类

public class Person {

private String firstName;
private String lastName;    


public Person (String a, String b){

firstName = a;
lastName = b;


}

public String getfirstName(){


    return firstName;
}

public void setfirstName(String firstName){


   this.firstName = firstName;
}

public String getlastName(){


    return lastName;
}

public void setlastName(String lastName){

this.lastName = lastName;
}
}

我的类创建对象并调用toString

public class DvdTest {


private DVD d1;

public static void main (String [] args){

Person p2 = new Person ("Leonardo", "Decaprio");

DVD d1 = new DVD ("Inception",p2,4); 

System.out.println (p2.toString());

}
}

4 个答案:

答案 0 :(得分:3)

DVD类一样,您也需要覆盖toString()类中的Person方法。目前,它是从toString()的默认实现返回的打印值,类似于此

getClass().getName() + '@' + Integer.toHexString(hashCode())

以下是您使用的IDE生成的示例示例。

@Override
public String toString() {
    return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}

答案 1 :(得分:1)

当您尝试打印类型为leadActor的{​​{1}}时,会调用PersonPerson方法。默认toString方法打印由toStirng字符分隔的类名和哈希。这就是为什么在你的输出中你看到了这个:

@

为了以漂亮的方式打印Person对象,您还需要覆盖Person@10ed7f5c 类中的toString方法。这是使用eclipse生成的字符串实现:

Person

答案 2 :(得分:1)

这不是错误的输出。

默认的toSTring of Object返回此值。类+哈希码

如果您想要自定义消息覆盖toString of Person

public String toString() {
    return "Person [firstName=" + firstName + ", lastName=" + lastName + "]";
}

注意:您已在DVD课程中完成此操作。

答案 3 :(得分:1)

您必须覆盖toString()方法:

@Override
public String toString() {
    return String.format("Person [firstName=%s, lastName=%s]", firstName, lastName);
}