I want to add a toString
method in the Item
class that returns the title of the item in there.
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
is the superclass and DVD
is the subclass.
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.o开发者_C百科ut.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);
}
}
Item toString
:
public String toString()
{
return title;
}
DVD toString
:
public String toString()
{
return super.toString() + " director: " + director;
}
Also, I don't know what you're trying to do with this but I would put those print()
methods in these classes.
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
)
Cheers
A toString
method is already defined in each Java class (it inherits the toString
of Object
). But it will return a practically meaningless value (AFAIR, the internal address/id of the instance within the JDK - I might be wrong).
What you need to do is to override that method and make it return a String
that is the title of the Item
. For the DVD class, you have to override toString
and make it a string made up of the concatenation of the title and director.
For the Item
class, your method should look something like this:
public String toString(){
return this.title;
}
You should be able to use the same idea to implement toString
for DVD.
精彩评论