简体   繁体   English

在Java中打印对象变量会发生什么情况?

[英]What happens what you print the variable of an object in java?

public class test
{
        public static void main (String[ ] args )
        {
            TheClass one = new TheClass(); constructor
            TheClass two = new TheClass(str , doubleNum); // I: calling the parameter constructor to //pass: “David William” and 3.5 to the object
            System.out.println( one );   
            System.out.println( two );   

            // call the method staticMethod
            System.out.print(two.staticMethod());
        }
}


class TheClass
{

     private String str;
     private static int intNum = 0;
     private double doubleNum ;


     public TheClass()
     {
          str = "unknown";
          doubleNum = 0.0;
     }

     public TheClass (String s, double d)
     {
          str = s;
          doubleNum = d;
     }

     public static void staticMethod ()
     {
          intNum ++;
     }
}

Would it make sense to do "System.out.println( one );" 进行“ System.out.println(one);”有意义吗? & "System.out.println( two );" &“ System.out.println(两个);” since they are only constructors? 因为他们只是构造函数? What would the output be for these 2 lines? 这两条线的输出是什么?

Since you haven't defined a toString() method, the output of "printing" an instance of you class will be not useful to a human. 由于尚未定义toString()方法,因此“打印”您的类的实例的输出对人类没有用。

Assuming you defined a meaningful toString() method, there is nothing wrong with the concept of printing an object just constructed, such as: 假设您定义了一个有意义的toString()方法,那么打印刚刚构造的对象的概念就没有问题,例如:

System.out.println( new TheClass(str , doubleNum) );

It just means that you wouldn't have a reference to the object after that line (and thus it would be available for garbage collection). 这只是意味着您在该行之后将没有对该对象的引用(因此该对象可用于垃圾回收)。

Try the same code but add this method to your class: 尝试相同的代码,但是将此方法添加到您的类中:

@Override
public String toString() {
    return str + " " + doubleNum;
}

If the class has an overridden toString() implementation, then that will be used and whatever string is returned by that implementation will be printed out. 如果该类具有重写的toString()实现,则将使用该类,并且将打印出该实现返回的任何字符串。 Otherwise, the JVM will try to see if it can find a toString() implementation for an ancestor of that class and use that. 否则,JVM将尝试查看是否可以为该类的祖先找到toString()实现并使用它。

Eventually, that is, if the JVM is not able to find a suitable overridden implemenation of .toString() , Object#toString() is called (every class in Java derives from Object ). 最终,就是说,如果JVM无法找到.toString()的合适的重写实现,则调用Object#toString() (Java中的每个类都源自Object )。 This results in an output that isn't very useful. 这导致输出不是很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM