gpt4 book ai didi

java - toString方法

转载 作者:行者123 更新时间:2023-12-01 07:14:47 25 4
gpt4 key购买 nike

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

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

Item 是父类(super class),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() 方法放在这些类中。

您最好返回字符串表示形式并将其打印在其他地方(这样您就可以在不模拟 System.out 的情况下测试此类)

干杯

关于java - toString方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5523447/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com