Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

How do we cast a Derived class to Base class

  Asked By: Aditi    Date: May 19    Category: Java    Views: 7391
  

My aim is to cast the Derived class object to a Base class object.
Pls look at the code
class Base
{
public int i;
Base()
{
i = 2;
}
public String toString()
{
return ("i = " + i);
}
}

class Derived extends Base
{
public int j;
Derived()
{
j = 4;
}
public String toString()
{
return ("i = " + i + " j = " + j);
}
}

public class Test
{
public static void main (String args[])
{
Derived d = new Derived();
Base b ;
b = (Base)(d);
System.out.println(b);
}
}

The expected result is i=2, but the actual result is i = 2 j = 4.
Is there any way to get the expected result.

Share: 

 

3 Answers Found

 
Answer #1    Answered By: Cheri Garcia     Answered On: May 19

As far as I know, you can't do that. When extending, you inheirit both
the implementation and the type. When you cast  the derived  class to
the base, you are using the type of the base  class. In a sense, this
is a contract that the derived class  must implement. Since the
relationship is extends, the type is implemented by inheiriting the
base class implementation. So, if the derived class did not override
the base clase toString(), then the base class implementation would be
used. Since you override the toString() in the derived class, this is
the toString() that gets invoked. In other words, you instantited a
derived class. That object  is a derived object that also implements
the type of the base class. But the object is still of type derived.

On a side note, I believe what you are asking can be implemented in
C++ or C# among other languages I assume.

Hope that helps and I may be off so hopefully others will correct me
where I was wrong.

 
Answer #2    Answered By: Julian Long     Answered On: May 19

Actually the right object  is being called. Its a
principal of polymorphism thru overriding. See even
though the refrence variable is of type Base the
object is that of the derived  class. Accoriding to
polymorphism thru overriding. If the method from the
parent class  is not over ridden in the child class
than the method from the parent class will be called
or else vice versa.

Check out the book by Bruce Eekel "Thinking in Java"

 
Answer #3    Answered By: Omar Walker     Answered On: May 19

what ever the way u used for casting is correct way and for ur required
output you can change the derived  class as follows:
class Derived extends Base
{
public String toString()
{
return ("i = " + i);
}
}
also instead of using these 3 steps for casting
Derived d = new Derived();
Base b ;
b = (Base)(d);
you can do it in a single step like
Base b=new Derived();
thats it over.

 
Didn't find what you were looking for? Find more on How do we cast a Derived class to Base class Or get search suggestion and latest updates.




Tagged: