gpt4 book ai didi

java - "Object"对象类型转换和对 "Some"类对象的引用

转载 作者:行者123 更新时间:2023-12-02 00:10:14 25 4
gpt4 key购买 nike

为什么我无法引用类型转换并引用某些类的对象的“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";

}

}

最佳答案

如果您确实希望参数的类型为 Object,则需要将 Object 转换为 Simple:

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 的方法,但反之则不然。

关于java - "Object"对象类型转换和对 "Some"类对象的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12982302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com