java派生类,Java;将基类转换为派生类

Why can't I cast a base class instance to a derived class?

For example, if I have a class B which extends a class C, why can't I do this?

B b=(B)(new C());

or this?

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){...}

}

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){

...

}

}

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.

Alright so I ended up figuring it out, partly thanks to Maruice Perry's answer.

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.

解决方案

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" );

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值