【问题标题】:can a method get called automatically? [duplicate]可以自动调用方法吗? [复制]
【发布时间】:2020-06-23 01:32:23
【问题描述】:

考虑下面的两个类,为什么当我在第二个类中调用 print 方法时,我得到“blueblueblue is blue repeat”而不是“blueblueblue”,尽管从未调用过 tostring()

public class Simple{ 
     private String word; 
     private String phrase; 
     public Simple(int number, String w) {  
          word = w;     
          phrase = mystery(number, w);          
     }   
     private String mystery(int num, String s) {    
          String answer = "";   
          for (int k=0; k<num; k++) {       
               answer = answer + s;     
          }     
          return answer; 
     } 

     public String toString() {     
          return phrase + " is " + word + " repeated";
     }
}
public class TestSimple{
     public void print() {      
          Simple item = new Simple(3, "blue");      
          System.out.println(item);             
     }      
}

【问题讨论】:

  • 您能否详细说明为什么您希望打印"blueblueblue"?您如何看待System.out.println 将您的对象转换为字符串表示形式?你知道toString 是一个继承自Object 的方法,你正在重写它吗?

标签: java


【解决方案1】:

是的,系统最终会调用 对象的 toString 方法。你可以得到源代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-08
    • 2013-05-03
    • 2011-03-31
    • 2011-08-20
    • 2017-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多