0 java
我想toString在Item类中添加一个返回项目标题的方法.
我需要确保类中的toString方法DVD调用该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);
}
Run Code Online (Sandbox Code Playgroud)
}
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);
}
Run Code Online (Sandbox Code Playgroud)
}
项目toString:
public String toString()
{
return title;
}
Run Code Online (Sandbox Code Playgroud)
DVD toString:
public String toString()
{
return super.toString() + " director: " + director;
}
Run Code Online (Sandbox Code Playgroud)
另外,我不知道你要做什么,但我会把这些print()方法放在这些类中.
您将更好地返回字符串表示并将其打印到其他位置(使用此功能,您可以在不进行模拟的情况下测试此类System.out)
干杯
| 归档时间: |
|
| 查看次数: |
2827 次 |
| 最近记录: |