tags:

views:

454

answers:

5

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.

A: 

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.

Kevin Montrose
public static ClassA getClassA(String a, String b);public class ClassA extends AnotherClass implements Runnable;Sorry I cannot post implementation
jbu
A: 

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.

MatrixFrog
This answers the error you were encountering, not the error the person asking the question was.
Clay
+3  A: 

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

Pavel Minaev
if so, try the cast as - java.lang.Object obj = getClassA();
Nate
+2  A: 

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());
}
Arun P Johny
A: 

Native types in java (int, long, short, char, double, float..) are not objects and hence do not have Object as an ancestor.

Thorbjørn Ravn Andersen