Tujuan Metode Overriding toString () ing Jawa

Apa gunane toString() cara ing jawa?

Yen kita pengin makili obyek kelas minangka String, mula kita bisa nggunakake toString() cara sing ngasilake perwakilan teks saka obyek kasebut.

Nalika sampeyan nyithak obyek, kanthi standar compiler Java njaluk toString() cara ing obyek. Dadi kanthi ngilangi toString() cara, kita bisa nyedhiyakake output sing migunani.


Ayo ndeleng konsep iki ing conto ing ngisor iki:



Cara Overriding toString ()

package io.devqa.tutorials; public class ToStringExample {
private String firstName;
private String lastName;
private String email;
public ToStringExample() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append('First name : ').append(this.firstName).append(' ');
sb.append('Last name : ').append(this.lastName).append(' ');
sb.append('Email : ').append(this.email).append(' ');
return sb.toString();
}
public static void main(String args[]) {
ToStringExample example = new ToStringExample();
example.setFirstName('Testing');
example.setLastName('Tester');
example.setEmail('testing@tester.com');

System.out.println(example);
} }

Kode ing ndhuwur ngasilake kaya ing ngisor iki:


First name : Testing Last name : Tester Email : testing@tester.com

Yen kita ora ngalahake toString() cara, output bakal wis



io.devqa.tutorials.ToStringExample@60e53b93

Kaya sing bisa dideleng, kanthi ngilangi toString() cara, kita bisa ngasilake presentasi sing migunani kanggo obyek kasebut.