gpt4 book ai didi

java - 转换实例/引用?

转载 作者:行者123 更新时间:2023-12-01 17:33:33 24 4
gpt4 key购买 nike

嗨,我对某事有点困惑。

假设我有类 A 和 B。A 是 B 的父类(super class)。如果我有一个返回类型为 A 的方法,我可以使用它作为返回值吗:

public class test{
private B b;//remember: A is super class of B so 'public class B extends A'

public test(){
b = new B();
}

public A geta(){
return (A)b;
}
}

因此,“geta()”返回的值将是对“b”实例的引用,该实例被转换为 A,因此,例如,如果 A 有变量 X 并且 B 有变量 Y,我将能够执行以下操作这个:

test t = new test(); //t.b.X = 5 and t.b.y = 10
A a = t.geta();
a.X = 20 /*This will change the value of X in the instance of B, b, of t...
in other words, t.b.X will also equal 20*/

非常感谢任何帮助,感谢您的宝贵时间!

最佳答案

geta 只能返回 b; 因为 b 是 A。

关于java - 转换实例/引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8597584/

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