• Post Reply Bookmark Topic Watch Topic
  • New Topic

Casting an Object to a Class  RSS feed

 
Larry Frissell
Ranch Hand
Posts: 82
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The following code is giving me compile errors on line 11, when I try to cast an Object to an Employee class. If I made a class without extending ArrayList, casting would not be a problem. I am not sure what the rules are that are causing the compile errors when I extend ArrayList.



Error
cannot find symbol
symbol : method getName()
location: class java.lang.Object
e.getName();// compile errors

 
Kevin Workman
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's a lot wrong there, but let me just get the stupid question out of the way:

Are you sure this is exactly the code you're running? Are you sure you aren't calling o.getName()?

Posting an SSCCE would help clear up any confusion about what you're doing, which would help you get better assistance.
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Larry Frissell wrote:

Don't you mean Right now, Employee is a generic type, not the actual class. Since the type is unbound the only thing the compiler can guarantee is that Employee is or (directly / indirectly) extends Object. That's why it shows you that error - Object doesn't have a getName() method.
 
Larry Frissell
Ranch Hand
Posts: 82
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Rob, when I remove the <Employee> from Staff and put ArrayList <Employee> the code works fine.
 
Vishal K Prasad
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Removed my reply as already correct reply was posted
 
Kevin Workman
Ranch Hand
Posts: 151
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vishal K Prasad wrote:Can you also check the import for Employee class? May be you two copy of Employee class in your classpath and the one imported here does not have the method. Just a wild guess. Posting the whole code might help.

No. The solution posted was correct and solved the problem. No wild guesses required.
 
Wouter Oet
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The term casting an Object is wrong. You can't cast an Object. You can however cast a reference.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!