演员实例/参考?

Ale*_*llo 0 java casting reference return-type return-value

嗨,我有点困惑的事情.

假设我有A类和B类.A是B的超类.如果我有一个返回类型为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;
    }
}
Run Code Online (Sandbox Code Playgroud)

因此'geta()'返回的值将是对作为A的'b'实例的引用,例如,如果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*/
Run Code Online (Sandbox Code Playgroud)

非常感谢任何帮助,谢谢你的时间!

Ray*_*yek 5

geta可以return b;因为b是A.