Why am I not able to reference object of “Object” class typecasted and referenced to Some class’s object. Following code explains it. It is hard to put in words. Meaning, object of Super class Object should be able to reference any type of Class’s object.
public class ChildClass {
public static void main(String[]args){
Simple obj1=new Simple();
Object obj2=(Simple)obj1;
System.out.println("1-obj1.a is "+ obj1.a+" obj1.name is "+obj1.name);
System.out.println("2-obj2.a is "+ obj2.a+" obj2.name is "+obj2.name);/*a cannot be resolved or is not a
field*/
doSomething(obj2);
System.out.println("3-obj2.a is "+ obj2.a+" obj2.name is "+obj2.name);/*a cannot be resolved or is not a
field*/
System.out.println("4-obj1.a is "+ obj1.a+" obj1.name is "+obj1.name);
}
private static void doSomething(Object obj2) {
obj2.a=99;//a cannot be resolved or is not a field
obj2.name="new name";//name cannot be resolved or is not a field
}
class Simple {
int a=9;
String name="something";
}
}
You need to cast the
ObjecttoSimpleif you really want the argument to be of typeObject:or, to make it a little more safe:
You seem to have it backwards. A reference of type
Simplecan be used to call methods ofObject, but not the other way around.