java: "downcasting" to new object / opposite of slicing
Posted
by
rhavin
on Stack Overflow
See other posts from Stack Overflow
or by rhavin
Published on 2011-03-23T22:57:03Z
Indexed on
2012/04/05
11:28 UTC
Read the original article
Hit count: 254
java
|downcasting
Sorry, i really dont know how to make a headline for that question; maybe there is a name for what im trying to do that i dont know, but i can explain it with some code:
Guess you have a class that unfortunately neither has a copy-constructor nor a public static copy method.
class A
{
private int i; // <- private, cant access
String x; // <- even worse: cant access unless in same pkg!
/* … other stuff, ctor, etc. … */
public A clone()
{
A a = new A();
a.i = i;
a.x = x;
return x;
}
}
Guess further, there is some function that returns an object of that class:
public static A someFn(x,y,z);
Now the problem: I want to derive from that class to add some functionality. Unfortunately, i neither have a sizeof in java nor a cc or static copy method.
So when i do a
class B extends A
{
protected w;
public B clone()
{
/* as usual */
}
}
then i can clone my B and get a new one, but how can i convert the returned A from someFn() into a B. Is there anyway to do the opposite of slicing in java? if i clone it, it's still an A, and i cant copy it field by field. This is all simple in c++, but how to do this in Java?
© Stack Overflow or respective owner