toString方法 [英] toString method

查看:83
本文介绍了toString方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to add a toString method in the Item class that returns the title of the item in there.

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

I have need make sure that the toString method in the DVD class calls the toString method in Item so that it can return a string that contains both the title and the 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);
}

}

推荐答案

toString

public String toString()
{
  return title;
}

DVD toString

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

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

Also, I don't know what you're trying to do with this but I would put those print() methods in these classes.

您最好返回字符串表示并将其打印到其他位置(使用此功能,您可以测试此类而无需模拟 System.out

You will be better of returning the string representation and printing it somewhere else (with this you can test this class without mocking System.out)

干杯

这篇关于toString方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆