简体   繁体   中英

Print object values in toString

I wants to override toString() method to show name of user but Name is the inner class of User class so how can I print it.

public class User
{
    public static class Name 
    {
        private String _first, _last;

        public String getFirst() { return _first; }
        public String getLast() { return _last; }

        public void setFirst(String s) { _first = s; }
        public void setLast(String s) { _last = s; }
    }
    private Name _name;
    public Name getName() { return _name; }
    public void setName(Name n) { _name = n; }

    @Override
    public String toString()
    {
        return "";//How to print first name and last name here
    }
}

Try like this

@Override
    public String toString() {
        return _name.getFirst()+_name.getLast();
    }

How about

public String toString()
{
    Name name = getName();
    return name.getFirst() + " " + name.getLast();
}

Try this:

@Override
public String toString()
{
    String a = getName()._first;
    String b = getName()._last;
    return "a: " + a + " :: b: " + b;//How to print first name and last name here
}

User user = new User();
User.Name name = new User.Name();
name.setFirst("first name");
name.setLast("last name");
user.setName(name);
System.out.println(user);

If you want to return for example John Deer you can try this code:

@Override
    public String toString()
    {
        return _name.getFirst().concat(" ").concat(_name.getLast());
    }

concat(string str) appends the string str to the end of the String object it is called on. You can read more about it on the link.

The snippet provided above will read First Name from _name , append an empty space just after it and then append the Last name on the final string.

@Override
    public String toString()
    {
        return _name.getFirst() + " " + _name.getLast();
    }

Call like this.

public class MyMain {
    public static void main(String[] args) {
        User.Name name = new Name();
        name.setFirst("Clement");
        name.setLast("Alexandria");
        User user = new User();
        user.setName(name);
        System.out.println(user);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM