jbu
jbu

Reputation: 16131

Java: Why can't I cast this to an Object?

This is bizarre... I thought every object in java had Object as an ancestor.

I have a ClassA that extends my ClassB and implements Runnable.

After creating ClassA I cannot cast it to an Object.

Assume getClassA returns a ClassA instance.

I am doing

Object obj = getClassA();

I also tried

Object obj = (Object) getClassA();

I get an incompatible types compile error: found Class, required Object.

What's the deal with that? I thought all objects could be cast to Object.

Edit: I assume it has something to do with the fact that ClassA implements Runnable, but I am not sure and need an explanation.

Edit2: Changing getClassA() to return an Object allows the program to compile.

Edit3: Importing the package that contained ClassB fixed the problem. Class B was defined in a different jar. ClassA was defined in another jar that referenced the jar containing ClassB.

Upvotes: 3

Views: 16811

Answers (4)

Arun P Johny
Arun P Johny

Reputation: 388316

How you are compiling the java file. Can you give some more information about getClassA(). What is the return type of this method?

The type casting is unnecessary since all objects in java are of type Object.

If you are using a IDE like eclipse you can put a break point on the line where you are assigning the Object obj = getClassA(); and inspect the value returned by getClassA().

Else you can try to put a instanceof condition before assigning the value to obj.

if(getClassA() instanceof Object){
    Object obj = getClassA();
}else{
    System.out.println("getClassA() is not retuning an object: "+ getClassA());
}

Upvotes: 2

Pavel Minaev
Pavel Minaev

Reputation: 101585

Do you by chance have a class named Object somewhere in your code (or non-standard packages that it imports)?

Upvotes: 6

Tyler
Tyler

Reputation: 22116

I tried this in Eclipse and got an "unnecessary cast" warning. You can probably configure it so that is an error instead of a warning, so I would guess that's what you did.

Upvotes: -4

Kevin Montrose
Kevin Montrose

Reputation: 22581

Class does descend from Object. There's something else going on here.

If you're code really is:

//...Code
Object obj = MyObject.getClassA();
//More Code...

class MyObject{
  static Class getClassA(){...}
}

It should work. Show us the code for an actual answer.

Upvotes: 1

Related Questions