toString方法

时间:2011-04-02 13:29:59

标签: java

我想在toString类中添加一个Item方法,该方法返回该项目的标题。

我需要确保DVD类中的toString方法调用toString中的Item方法,以便它可以返回包含title和director的字符串。

Item是超类,DVD是子类。

  public class Item
   {
  private String title;
  private int playingTime;
  private boolean gotIt;
  private String comment;

public Item(String theTitle, int time)
{
    title = theTitle;
    playingTime = time;
    gotIt = false;
    comment = "<no comment>";
}

// Getters and setters omitted

public void print()
{
    System.out.print(title + " (" + playingTime + " mins)");
    if(gotIt) {
        System.out.println("*");
    } else {
        System.out.println();
    }
    System.out.println("    " + comment);
}

}

 public class DVD extends Item 
 {
 private String director;

public DVD(String theTitle, String theDirector, int time)
{
    super(theTitle, time);
    director = theDirector;
}

// Getters and setters omitted

public void print()
{
    System.out.println("    director: " + director);
}

}

2 个答案:

答案 0 :(得分:6)

项目toString

public String toString()
{
  return title;
}

DVD toString

public String toString()
{
  return super.toString() + " director: " + director;
}

另外,我不知道你要做什么,但我会把这些print()方法放在这些类中。

您最好返回字符串表示并将其打印到其他位置(使用此功能,您可以在不模仿System.out的情况下测试此类)

干杯

答案 1 :(得分:2)

每个Java类中已经定义了toString方法(它继承了toString的{​​{1}})。但它会返回一个几乎没有意义的值(AFAIR,JDK中实例的内部地址/ id - 我可能错了)。

您需要做的是覆盖该方法,并使其返回Object String的标题。对于DVD类,您必须覆盖Item并使其成为由标题和导演的串联组成的字符串。

对于toString类,您的方法应如下所示:

Item

您应该能够使用相同的想法为DVD实施public String toString(){ return this.title; }