user2556900
user2556900

Reputation:

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( two );" since they are only constructors? What would the output be for these 2 lines?

Upvotes: 0

Views: 287

Answers (2)

Vivin Paliath
Vivin Paliath

Reputation: 95528

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. Otherwise, the JVM will try to see if it can find a toString() implementation for an ancestor of that class and use that.

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). This results in an output that isn't very useful.

Upvotes: 0

Bohemian
Bohemian

Reputation: 425053

Since you haven't defined a toString() method, the output of "printing" an instance of you class will be not useful to a human.

Assuming you defined a meaningful toString() method, there is nothing wrong with the concept of printing an object just constructed, such as:

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;
}

Upvotes: 1

Related Questions