I need to create a sub-class of a existing class, which I know how to do, but I need to be able to create the subclass based off a existing super class without modifying the super class.
For example:
public class Foo
{
public Foo(int a)
{
_a = a;
}
private int _a;
}
public class Bar extends Foo
{
public Bar(int a, int b)
{
super(a);
_b = b;
}
public Bar(Foo foo, int b)
{
???? //<----What do I do here?
_b = b;
}
private int _b;
}
public static class Baz
{
static void Main(String[] args)
{
Foo foo = new Foo(1);
Bar bar = new Bar(foo, 2); //<---- How do I set this up?
}
}
So in the above example it would use the existing instance of Foo and turn it in to a Bar and set the _b field to 2.
EDIT
Important constraint, I did not think everyone would tell me to edit Foo. I can not change Foo, that class is in a library I can not edit, so what I want to do needs to be done without editing Foo.
EDIT2
Here is the actual Foo, it is the ChunkProvider class from Minecraft.
public class ChunkProvider
implements IChunkProvider
{
public ChunkProvider(World world, IChunkLoader ichunkloader, IChunkProvider ichunkprovider)
{
chunkSet = new HashSet();
chunkMap = new HashMap();
chunkList = new ArrayList();
field_28064_b = new EmptyChunk(world, new byte[32768], 0, 0);
field_28066_g = world;
field_28069_d = ichunkloader;
field_28070_c = ichunkprovider;
}
//(Snip) There are no GetXXX members for the below fields.
private Set chunkSet;
private Chunk field_28064_b;
private IChunkProvider field_28070_c;
private IChunkLoader field_28069_d;
private Map chunkMap;
private List chunkList;
private World field_28066_g;
}
There is a way around this, and it is not to inherit
Foo, but to compose it and delegate to its methods.I noticed that the “real”
Fooimplements an interface. If you could design your code around that interface and not around the concreteFoo,Barcan be like this: