toString method

前端 未结 2 1863
北恋
北恋 2020-12-22 06:16

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 met

相关标签:
2条回答
  • 2020-12-22 07:00

    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.

    0 讨论(0)
  • 2020-12-22 07:05

    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

    0 讨论(0)
提交回复
热议问题