Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java; casting base class to derived class

Tags:

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.

like image 874
Cam Avatar asked Apr 03 '10 19:04

Cam


People also ask

Can we assign base class to derived class?

No, that's not possible since assigning it to a derived class reference would be like saying "Base class is a fully capable substitute for derived class, it can do everything the derived class can do", which is not true since derived classes in general offer more functionality than their base class (at least, that's ...

Can we call derived class method from base class in Java?

1. an instance of a derived Class can call methods, and set/get public variables/fields, of its Base Class even if an instance of the Base Class has never been created.

Can you cast a superclass to a subclass?

You can try to convert the super class variable to the sub class type by simply using the cast operator. But, first of all you need to create the super class reference using the sub class object and then, convert this (super) reference type to sub class type using the cast operator.

What does a derived class inherit from the base class Java?

A derived class inherits all the nonprivate members of its base class.


1 Answers

because if B extends C, it means B is a C and not C is a B.

rethink what you are trying to do.

like image 62
Omry Yadan Avatar answered Oct 21 '22 19:10

Omry Yadan