Syntax Error
Cannot find symbol: method 'equals(Object)' in class 'MyString'
What This Error Means
This error occurs when the Java compiler is unable to find a method declaration in the class or interface being used. In this case, the error is related to overloading a method.
Why It Happens
This error typically happens when you're trying to use a method or variable that doesn't exist in the class or interface. In this specific scenario, you're trying to override the 'equals(Object obj)' method, but you're not declaring it in your class.
How to Fix It
- 1To fix this error, you need to declare the 'equals(Object obj)' method in your class. Here's how to do it:
- 2public boolean equals(Object obj) {
- 3 if (this == obj) {
- 4 return true;
- 5 }
- 6 if (obj == null || getClass() != obj.getClass()) {
- 7 return false;
- 8 }
- 9 MyString other = (MyString) obj;
- 10 return Objects.equals(this.value, other.value);
- 11}
- 12You can also use the '@Override' annotation to let the compiler know that you're trying to override a method.
Example Code Solution
❌ Before (problematic code)
Java
class MyString {
private String value;
public boolean equals(String other) {
return this.value.equals(other);
}
}✅ After (fixed code)
Java
class MyString {
private String value;
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
MyString other = (MyString) obj;
return Objects.equals(this.value, other.value);
}
}Fix for Cannot find symbol: method 'equals(Object)' in class 'MyString'
Browse Related Clusters
Related JAVA Errors
Related JAVA Blog Articles
Have a different error? Get an instant explanation.
Explain Another Error