English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce tutoriel, nous allons apprendre à imprimer des objets de classes en Java.
Pour comprendre cet exemple, vous devriez comprendre ce qui suitJava programmationThème :
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
Dans l'exemple ci-dessus, nous avons créé un objet de la classe Test. Lorsque nous imprimons l'objet, nous pouvons voir que la sortie semble différente.
C'est parce que lors de l'impression d'un objet, la méthode toString() de la classe de l'objet est appelée. Elle formatte l'objet dans un format par défaut. Voici un exemple :
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().