Why are you returning the path of class

Asked

Viewed 31 times

0

I’m making a simple schedule and when I go to print the values shows the class path.

Why is this happening?

The message the console shows

[br.novo.itdd.Person@15db9742, br.novo.itdd.Person@6d06d69c]

My Main class

public static void main(String[] args) {
    Schedule schedule = new Schedule();

    schedule.addContact("claro", "1052");
    schedule.addContact("oi", "10331");
    System.out.println(schedule.getPerson());
}

Class Schedule

import java.util.List;
import java.util.ArrayList;

public class Schedule {

    private List<Person> person;

    public Schedule() {
        this.person = new ArrayList<Person>();
    }

    public void showSchedule(){
        System.out.println(this.getPerson());
    }

    public List<Person> getPerson() {
        return person;
    }   

    public boolean addContact(String name, String number){

        this.person.add(new Person(name, number));
        return true;
    }
}

Class Person

public class Person {           
    private String name, cellNumber;

    public Person(String name, String cellNumber) {
        this.setName(name);
        this.setCellNumber(cellNumber);
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        if(name.length() >= 2) {
            this.name = name;
        }
    }

    public String getCellNumber() {
        return cellNumber;
    }

    public void setCellNumber(String cellNumber) {
        if (cellNumber.length() >= 4) {
            this.cellNumber = cellNumber;
        }
    }

    public boolean validateDate() {

        return true;
    }
}

1 answer

2


It is because this is the standard implementation of the method toString(). You can see more about this in the post: Doubts about the toString() method of the Object class

You can specify what you want to print in the method call println or else overwrite the toString().

Specifying in println

Person person = schedule.getPerson();
System.out.println(
  String.format("Name: %s, Cellphone: %s", person.getName(), person.getCellNumber()));

Rewriting the toString()

public class Person {
    // ...
    @Override
    public string toString() {
        return String.format("Name: %s, Cellphone: %s", getName(), getCellNumber());
    }   
}
  • Thank you was right

  • @Thor, you are welcome. Just for the record: Whenever you ask a question and it’s answered, you can mark the answer that suits you best as correct using the on her left side.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.