“对象”对象类型转换和对“某些”类对象的引用

时间:2012-10-19 20:52:33

标签: java object casting

为什么我无法引用类型为“Object”类的对象并引用某些类的对象。以下代码解释了它。很难说出来。意思是,Super class Object的对象应该能够引用任何类型的Class对象。

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";

}

}

3 个答案:

答案 0 :(得分:1)

如果您确实希望参数属于Object类型,则需要将Simple强制转换为Object

private static void doSomething(Object obj2) {
    ((Simple)obj2).a = 99;
    ((Simple)obj2).name = "new name";
}

或者,为了让它更安全一点:

private static void doSomething(Object obj2) {
    if (obj2 instanceof Simple) {
        Simple simple = (Simple) obj2;  
        simple.a = 99;
        simple.name = "new name";
    }
}

你似乎倒退了。 Simple类型的引用可用于调用Object的方法,但不能反过来。

答案 1 :(得分:1)

做上面的Keppil建议。

或者,因为您将obj2转换为Simple类型,只需将doSomething的参数更改为该类型:

private static void doSomething( Simple simple ) { 
    simple.a=99;
    simple.name="new name";
}

您还应该更改

Object obj2=(Simple)obj1;

Simple obj2 = (Simple)obj1;

答案 2 :(得分:1)

您正在尝试引用存在于Simple类实例中的字段,但您没有将对象类型转换为Simple实例。

已赋值变量obj2来保存Simple的实例,但它已被声明为Object类型。如果没有明确地转换为Simple类型,编译器只能假设obj2具有Object类型的函数。

我没有测试过这段代码,但它应该得到重点。注意每当我引用Simple类型中声明的任何字段时,我都会将obj2强制转换为Simple。

public class ChildClass {

public static void main(String[]args){
    Simple obj1=new Simple();
    Object obj2=obj1;
    System.out.println("1-obj1.a is "+ obj1.a+" obj1.name is "+obj1.name);
    System.out.println("2-obj2.a is "+ ((Simple)obj2).a+" obj2.name is "+((Simple)obj2).name);
    doSomething((Simple)obj2);
    System.out.println("3-obj2.a is "+ ((Simple)obj2).a+" obj2.name is "+((Simple)obj2).name);
    System.out.println("4-obj1.a is "+ obj1.a+" obj1.name is "+obj1.name);
}

    private static void doSomething(Simple 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";
    }
}