问题描述
为什么不能将基类实例转换为派生类?
Why can't I cast a base class instance to a derived class?
例如,如果我有一个类B扩展类C,为什么我这样做?
For example, if I have a class B which extends a class C, why can't I do this?
B b=(B)(new C());
或此?
C c=new C();
B b=(B)c;
好吧,让我更明确一点我试图做。这是我有的:
Alright let me be more specific as to what I'm trying to do. Here's what I have:
public class Base(){
protected BaseNode n;
public void foo(BaseNode x){
n.foo(x);
}
}
public class BaseNode(){
public void foo(BaseNode x){...}
}
现在我想创建一组扩展Base和Basenode的类,如下所示:
Now I want to create a new set of classes which extend Base and Basenode, like this:
public class Derived extends Base(){
public void bar(DerivedNode x){
n.bar(x);//problem is here - n doesn't have bar
}
}
public class DerivedNode extends BaseNode(){
public void bar(BaseNode){
...
}
}
想要通过扩展它们和向它们添加一个函数来向Base和BaseNode添加新的功能。此外,Base和BaseNode应该能够自己使用。
So essentially I want to add new functionality to Base and BaseNode by extending them both, and adding a function to both of them. Furthermore, Base and BaseNode should be able to be used on their own.
如果可能的话,我真的想没有泛型。
I'd really like to do this without generics if possible.
好吧,所以我结束了这一切,部分是由于Maruice Perry的回答。
Alright so I ended up figuring it out, partly thanks to Maruice Perry's answer.
在我的 Base
的构造函数中, n
被实例化为 BaseNode
。所有我要做的是在我的派生类中的构造函数中重新实例化 n
为 DerivedNode
In my constructor for Base
, n
is instantiated as a BaseNode
. All I had to do was re-instantiate n
as a DerivedNode
in my derived class in the constructor, and it works perfectly.
推荐答案
您需要使用 instanceof 由 n 引用的对象类型,并对该对象进行类型转换并调用 bar() 签署 Derived.bar() 方法
You need to use the instanceof keyword to check the type of object referenced by n and typecast the object and call the bar() method. Checkout Derived.bar() method bellow
public class Test{
public static void main(String[] args){
DerivedNode dn = new DerivedNode();
Derived d = new Derived(dn);
d.bar( dn );
}
}
class Base{
protected BaseNode n;
public Base(BaseNode _n){
this.n = _n;
}
public void foo(BaseNode x){
n.foo(x);
}
}
class BaseNode{
public void foo(BaseNode x){
System.out.println( "BaseNode foo" );
}
}
class Derived extends Base{
public Derived(BaseNode n){
super(n);
}
public void bar(DerivedNode x){
if( n instanceof DerivedNode ){
// Type cast to DerivedNode to access bar
((DerivedNode)n).bar(x);
}
else {
// Throw exception or what ever
throw new RuntimeException("Invalid Object Type");
}
}
}
class DerivedNode extends BaseNode{
public void bar(BaseNode b){
System.out.println( "DerivedNode bar" );
}
}
这篇关于Java;将基类转换为派生类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!