This is my class containing setters and getters
package Pack;
public class Details {
String FirstName,LastName,City,Country;
public Details(String firstName, String lastName, String city,
String country) {
super();
FirstName = firstName;
LastName = lastName;
City = city;
Country = country;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String firstName) {
FirstName = firstName;
}
public String getLastName() {
return LastName;
}
public void setLastName(String lastName) {
开发者_运维知识库 LastName = lastName;
}
public String getCity() {
return City;
}
public void setCity(String city) {
City = city;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
}
===========================================================================
This is my main()
package Pack;
public class MainClass {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Details d = new Details("Hari","L","Bangalore","India");
}
}
==========================================================================
I know my main() is incomplete. What should i write to display the contents of "d"?
There are two ways.
One, just print each property of your details object :
System.out.println("FirstName :"+d.getFirstName());
etc..
Or, a better option would be to override toString()
method in your class
public void toString() {
return this.getFirstName()+ " " + this.getLastName()+" "+.... ;
}
and then just print your class System.out.println(d);
you need a toString() method in Details class:
public String toString(){
return this.firstName + " " + this.lastName + ", " + this.city + " " + this.country;
}
and
System.out.println(d.toString());
in main
Override toString() method in Details as follow and then just call to print what you want:
public String toString(){
return this.firstName+" "+this.lastName+" "+this.city+" "+this.country;
}
in main just call it as System.out.println(d);
Something like this?
System.out.printf("%s %s (%s, %s)\n", d.getFirstName(), d.getLastName(), d.getCity(), d.getCountry());
I would make your fields (FirstName, LastName, City, and Country) private, otherwise there's not much point in using getters and setters.
Try to add methods (or something similar with more properties):
public String asFirstnameLastname()
{
return firstName + " " + lastName;
}
public String asLastNameFirstname()
{
return lastName + " " + firstName;
}
toString() is also a good choice.
精彩评论