Java basics: The toString method of the Object

Source: Internet
Author: User

Java basics: The toString method of the Object

I. First, check Demo1.

 

public class Dog1{Dog1(){}public static void main(String[] args) {Dog1 d = new Dog1();System.out.println(d);}}
Output result:

 

Dog1 @ 77aaf64d

What is the output result of an object? But have you ever wondered why this result is output?

 

To understand this output, you need to understand the Object class. The Object class is the base class of all java classes.

That is, the class definition above is equivalent

public class Dog1 extends Object{
The Object class has a toString () method.
Its implementation code is:
 public String toString() {  return getClass().getName() + @ + Integer.toHexString(hashCode());  }

 

System. out. println (d );
// Equivalent to System. out. println (+ d );
// Equivalent to System. out. println (+ d. toString (); www.bkjia.com
// Any object and String concatenation will convert the object to the string type, which is equivalent to calling the toString method of the object. The toString () method of the parent class will be called here

 

Ii. Check Demo2 again.

 

public class Dog2{Dog2(){} public String toString() {        return i am a dog;    }public static void main(String[] args) {Dog2 d = new Dog2();System.out.println(d);}

Let's see the output:

 

I am a dog

 

Why?

Because Dog2 overrides the Override toString () method of the parent class Object. You will call your own toString method.

It is recommended that you rewrite the toString () method of the Object.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.