【问题标题】:Printing object instance name returns value from random method? JAVA [duplicate]打印对象实例名称从随机方法返回值? JAVA [重复]
【发布时间】:2021-05-15 11:57:17
【问题描述】:

这是我的主要内容:

public class testMain
{
     public static void main ( String[] args )
     {
          testClass test = new testClass();
          System.out.println(test);
     }
}

这是我的课:

public class testClass
{
     private String word;

     public testClass(String s)
     {
          word = s;
     }

     public String toString()
     {
          return "test";
     }

 }

当我从 toString 方法打印 System.out.println(testClass) "test" 时。为什么?这个方法的返回是怎么执行的?

【问题讨论】:

  • 因为println 导致在参数上调用toString。你还期待什么其他印刷品?
  • 你真的认为被调用的方法是随机的吗?

标签: java class methods return


【解决方案1】:

当你这样做时

System.out.println(test);

它调用对象的 toString 方法。 默认情况下它返回类名和附加信息,但是你在你的类中定义了它(你覆盖了 Object 类的默认方法),所以在你的情况下它返回“test”

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-02
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 2012-08-17
    • 1970-01-01
    • 2012-09-20
    • 2016-02-01
    相关资源
    最近更新 更多