美文网首页
2018-10-18 Java toString() 方法的运用

2018-10-18 Java toString() 方法的运用

作者: 刘月林Yuelin_MELB | 来源:发表于2018-10-18 11:02 被阅读0次

    因为在java中 Object类是基类,所以每个类都会有toString方法,System.out.println(Object)实际上就是调用 object的 toString 方法

    public class Part1_1{
      public static void main(String[] args) {
        Author author1 = new Author("Richard Hartley", "123456@gamil.com", 'M');
        Book aBook = new Book("Multiple View Geometry",author1,100,10);
        Author author2 = new Author("Peter", "456789@gamil.com", 'F');
        aBook.AddAuthor(author2);
        System.out.print(aBook.toString());
        System.out.print("\n");
        aBook.RemoveAuthor("Peter");
        System.out.println(aBook); // 调用 aBook 的 toString()
      }
    }
    
      //重写过的 toString() 方法
      public String toString(){
        String str = "Author[ name = "+this.getName()+", email = "+this.getEmail()+", gender = "+this.getGender()+"]";
        return str;
      }
    

    输出

    Book[ name = Multiple View Geometry,[Author[ name = Richard Hartley, email = 123456@gamil.com, gender = M], Author[ name = Peter, email = 456789@gamil.com, gender = F]], price = 100.0, qty = 10]
    
    Book[ name = Multiple View Geometry,[Author[ name = Richard Hartley, email = 123456@gamil.com, gender = M]], price = 100.0, qty = 10]
    

    参考资料
    https://zhidao.baidu.com/question/16425045.html
    https://zhidao.baidu.com/question/582453879.html?qbl=relate_question_0&word=toString%28%29

    刘月林
    写于浙江宁波
    20181018

    相关文章

      网友评论

          本文标题:2018-10-18 Java toString() 方法的运用

          本文链接:https://www.haomeiwen.com/subject/xtejzftx.html