• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to cast private class to an object in equals method  RSS feed

 
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right now I am getting an error on line 1 for Word.java:1: error: modifier private not allowed here and line 28 for Word.java:28: error: cannot find symbol. I kind of get the reason why, but I do not know how to cast an object with private class if possible.

Thanks

 
Author and ninkuma
Marshal
Posts: 66307
152
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The error message says it all, you can't have a top-level private class. You can create private inner classes, though.
 
Sheriff
Posts: 22844
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As for how to cast an object to a known class: Your code



isn't correct. Here's how to cast to the Word class:



 
Abad Ashraf
Greenhorn
Posts: 27
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh thanks I did not notice I casted it wrong.
 
Ranch Foreman
Posts: 919
26
Android Chrome IntelliJ IDE Java MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please note, that if you override the equals method you should also override the hashCode method as explained here
https://coderanch.com/t/683598/java/override-equals-override-hashCode
 
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your toString method shou‍ld fail to compile too. It is supposed to return a String not print it.
I would suggest you handle the cast differently:-
return ((Word)o).w.equals(this.w);
Note that method will fall down horribly if w is ever null. You have to take precautions against that. Look at the Objects class and its equals method.
Don't print anything in the equals method (except for testing purposes).
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!