0

I wonder why this is legal:

Object mystring = "hello";
System.out.println(mystring);

This prints hello. But why Object is treated like a string ?

giò
  • 3,402
  • 7
  • 27
  • 54
  • 1
    If we look at the [Java docs for String](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html), we can see `public final class String extends Object`. This means Object is the parent class of String. It's basically the same as a class `Animal` and a class `Dog extends Animal`; in which case you can do `Animal pet = new Dog();`. – Kevin Cruijssen May 03 '16 at 14:40
  • `Object mystring` is a reference not an object. You can't have Object variables in Java. – Peter Lawrey May 03 '16 at 14:58

2 Answers2

5

Because a String IS-A Object, so a reference type can be any super types.

For instance, you could also assign mystring to a CharSequence type.

The println method of PrintStream (your System.out static field) has an overload to take String as an argument, and print it properly.

In this case though, the code in PrintStream#println(Object) will actually print String.valueOf(x), where x is your given argument.

Mena
  • 47,782
  • 11
  • 87
  • 106
3

It calls it's toString() method. The one that is implemented in the String class. Methods are binded at runtime.

user3719857
  • 1,083
  • 4
  • 16
  • 45
  • 1
    Nit: it doesn't simply call `Object.toString()`: it first checks for `null`, and prints `"null"` in that case; otherwise, it calls `toString()`. I can't remember if it actually calls `Objects.toString(obj)`, but it's logically the same. – Andy Turner May 03 '16 at 14:42