Huei Tan
Huei Tan

Reputation: 2315

use toString() in overload construct ? how

i have several Constructor in the class

public class Date {
       ...
       public Date(first case)
       ...
       public Date(second case)
       ...
       public Date(third case)
       ...
       public String toString(){
       ...}

How to write the code in toSTring() ????

Can any one explain to me

Upvotes: 0

Views: 151

Answers (4)

psabbate
psabbate

Reputation: 777

The toString method should represent the "state" of your object, so isn't related with constructors but with your class attributes.

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213261

What your toString returns is not decided by how many constructor you have in your class. They are used to return a String representation that you want to be printed when you print the instances of your class. You can return any field or concatenation of some fields from it.

So, if you have a Person class with some 4-5 fields including id and name and you want to print the id and name of the person separated by a colon, when you print the instanse, your toString() would look like:-

@Override
public String toString() {
    return this.id + " : " + this.name;
}

So, if you have an instance of Person class with id = 5, name = rohit, age = 23 and some email id, then when you display that instance: -

Person person = new Person(5, "rohit", "[email protected]", 23);
System.out.println(person);

Person person2 = new Person(6);  // Don't have `name` set
System.out.println(person2);

The above statement will print: -

5 : rohit
6 :

as output.

But you can of course put a condition in your toString to check whether a field is empty or not, and you can return a message accordingly.

Upvotes: 3

Kurtymckurt
Kurtymckurt

Reputation: 337

The java toString can be very useful for representing objects in text form. You should always overwrite toString() in order to have accessibility to proper debugging / logging. Here's a sample of a class that might make a good example.

public class Person {
    private final String _name;
    private final Integer _age;
    private final Date _birthday;

    public Person(String name, Integer age, Date birthday) {
        this._name = name;
        this._age = age;
        this._birthday = new Date(birthday.getTime());
    }

    @Override
    public String toString() {
        return "Person [_name=" + _name + ", _age=" + _age + ", _birthday="
                + _birthday + "]";
    }

}

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347234

public String toString() {
    return case1 != null ? case1 : case2 != null ? case2 : case3 != null ? case3 : null;
}

Upvotes: 0

Related Questions