Re: variable not recognised
Are you trying to override the equals function for Object? Object has no variable name, but your class does. If so, you must cast Object (highly recommended you check for null and that the parameter is an instanceof your class).
Re: variable not recognised
Quote:
Originally Posted by
gochi7
Code Java:
public class Person
{
private String name;
public Person()
{
name = "No name yet.";
}
public Person(String n)
{
name = n;
}
public void setName(String newName)
{
name = newName;
}
public String getName()
{
return name;
}
public void print()
{
System.out.println("Name: " + name);
}
public boolean equals(Object p)
{
return name.equals(p.name);
}
}
the only part that gives me trouble is p.name at the end it says it's not recognising varianle name but it was initialised at the top
Quote:
Are you trying to override the equals function for Object? Object has no variable name, but your class does. If so, you must cast Object (highly recommended you check for null and that the parameter is an instanceof your class).
It appears the OP is using the equals method of the String class.
This should work.
Code java:
public boolean equals(String name2)
{
if (getName().equals(name2))
return true;
return false;
}
Another possibility is:
Code java:
public boolean equals(Person p)
{
if (getName().equals(p.getName()))
return true;
return false;
}
And to avoid the null thing, have your Person(String name) constructor call the method setName(name);
Code java:
public Person(String name)
{
this.name = name;
setName(name);
}
Re: variable not recognised
Quote:
It appears the OP is using the equals method of the String class.
Which is defined in Object, not String
What makes you think that will work? equals is defined in Object, taking an Object as a parameter...define it any other way and and the behavior may not be what you expect (for example finding an object in a Collection will still use the method defined in Object). To check for equality beyond reference equality, you must override the Object.equals function as it is defined
Re: variable not recognised
Wait, you mean you have to do it this way:
Code java:
public boolean equals(Object obj)
{
if (obj instanceof Person)
{
if (getName().equals((Person) obj.getName()))
return true;
}
return false;
}
Wait...#-o that's how your override a method, true. I'd forgotten.
But isn't what i did earlier called overloading the method, which is also valid?
for instance