So I have a class called Person which looks like this
public class Person {
private String personName;
public String toString(){
return personName;
}
public Person(String personName){
this.personName = personName;
}
}
and another class in which I am creating the object(s) person
public class IdanJavaTask {
public static void main(String[] args) {
Person p1 = new Person("Bob");
System.out.println("p1 : " + p1);
Person p2 = new Person("Joe");
System.out.println("p2 :" + p2);
}
}
so far everything is fine and my print statement is
p1: Bob
p2: Joe
Now I want to create a new object, p3 and set it equal to p1 my class now looks like this:
public class IdanJavaTask {
public static void main(String[] args) {
Person p1 = new Person("Bob");
System.out.println("p1 : " + p1);
Person p2 = new Person("Joe");
System.out.println("p2 :" + p2);
Person p3 = new Person (p1);
System.out.println("p3 equal to p1:" + p3.equals(p1));
}
}
when I try to do this I get the following error message:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The constructor Person(Person) is undefined
at vehicleassignment.IdanJavaTask.main(IdanJavaTask.java:13)
I am thinking I will need to add a method to my main (Person) class, but I do not know why or what to add? why can't I just set the objects equal to eachother?
There are two ways to interpret "set the objects equal to each other".
One is that you want
p1
andp3
to refer to the same object. Like how Clark Kent and Superman are two names (references) for the same person. This would be accomplished by:In this scenario, if anything happens to
p1
, that same thing has happened top3
. If you kill Clark Kent, you have killed Superman (as they are one and the same). Java determines equality with theequals(Object o)
method - two objectsa
andb
are equal iffa.equals(b)
andb.equals(a)
returntrue
. These two objects will be equal using the baseObject
definition of equality, so you don't have to worry about that.The other way to interpret your meaning is to create a new person object, which happens to be an exact copy of the first person. In order to do this, you'd have to add another constructor to your person class that takes a person as an argument:
With this setup, you can do what you're doing in your main.
In order to make
p1
andp3
equal, we have to teach the Person class to use its fields for checking equality. We can do this by overriding theequals
method in class person.Whenever we overwrite the
equals
method, it is good practice to also overwrite thehashcode
method, which returns a uniqueint
for each Object. Since the only field that aPerson
object has is its name, we can simply use that hashcode.So all together, our Person class looks like this: