English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn how to print the object of a class in Java.
To understand this example, you should understand the followingJava programmingSubject:
class Test { } class Main { public static void main(String[] args) { // Create an object of the Test class Test obj = new Test(); //Print Object System.out.println(obj); } }
Output Result
Test@512ddf17
No exemplo acima, criamos um objeto da classe Test. Quando imprimimos o objeto, podemos ver que a saída parece diferente.
Isso é porque, ao imprimir um objeto, é chamado o método toString() da classe do objeto. Ele formata o objeto no formato padrão. Veja o exemplo a seguir:
Test - Class Name
@ - Concatenate Strings
512ddf17 - Object Hash Code
If you want to format the output in your own way, you need to override the toString() method in the class. For example,
class Test { @Override public String toString() { return "object"; } } class Main { public static void main(String[] args) { //Create an object of the Test class Test obj = new Test(); // Print Object System.out.println(obj); } }
Output Result
object
In the above example, the output has changed. This is because here we have overridden the method toString() that returns a string from the object.
To understand the method toString() of the object class, please visitJava Object toString().