我有两个类:
public class Base{
public Derived becomeDerived(){
Derived d = new Derived(this);
//set this pointer pointing to d,
//this = d; doesn't work
return d;
}
}
public class Derived extends Base{
public Derived(Base b){ }
}
是否可以通过示例中显示的方法更改当前对象的运行时类型?
我想这样做的原因是提供一种连接对象的方法。
我有
public abstract class Table{
}
和
public class ComplexTable extends Table{ }
这实际上是一个 Table
对象的链表。
我想提供一个方法,比如 Table.append(Table t)
,它不仅修改当前的 Table 对象,而且使它成为 ComplexTable
的实例.
最佳答案
没有。
在您的示例中,Base
不会变为 Derived
,它会返回一个新的 Derived
对象。
Base foo = new Base();
foo = foo.becomeDerived();
这可能是让您失望的原因,请记住变量不是对象,只是对对象的引用。因此,虽然您可以说 foo
从 Base
更改为 Derived
,但是 object 的运行时类型并没有为了不改变,您创建了一个具有不同运行时类型的新对象并重新分配了变量。
编辑: 更深入的示例。我给对象“命名”只是为了更容易理解。
Base foo = new Base();
/* After execution:
*
* Vars: | Objects:
* foo ----+---> a Base object (Name: Joe)
*/
foo = foo.becomeDerived();
/* After execution:
*
* Vars: | Objects:
* foo ----+---> a Derived object (Name: Phil)
* | a Base object (Name: Joe)(notice nothing references it)
*/
“Joe”的类型没有改变。 Joe 曾经并将永远是一个 Base
对象。这就是您所说的“对象的运行时类型”。但是,变量的运行时类型一直在变化!在这个例子中,foo
以Base
开始但变为 Derived
。
关于java - 是否可以通过其方法更改对象的运行时类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30401221/