Injongo yokuGqithisela kwiString () Indlela kwiJava

Yintoni injongo ye toString() indlela kwiJava?

Ukuba sifuna ukumela into yeklasi njenge-String, emva koko sinokusebenzisa toString() indlela ebuyisa into ebhaliweyo.

Xa ushicilela into, ngokungagqibekanga umhlanganisi weJava ubiza toString() indlela yento. Ke ngokugqitha toString() indlela, sinokubonelela ngemveliso enentsingiselo.


Makhe sibone lo mzekelo kulo mzekelo ulandelayo:



Ukugqithisa kwiString () Indlela

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);
} }

Le khowudi ingentla ikhupha oku kulandelayo:


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

Ukuba khange sibhale ngaphezulu toString() indlela, iziphumo bezizakuba

io.devqa.tutorials.ToStringExample@60e53b93

Njengoko kunokubonwa, ngaphezulu kwe- toString() indlela, sinokuvelisa umboniso onentsingiselo wento.