Reputation: 2657
Situtation:
class A {
private int prop = 0;
}
class B extends A {
private int extraProp;
B(int param){
extraProp = param
}
}
As you can see the only different is one extra property introduced to B.
I basically want to be able to add on the extra property to A, while casting it into B.
Is this possible without manually copying all properties from class A to B? Like this
class B extends A {
private final int extraProp;
B(int param){
extraProp = param
}
static B from(A a, int param){
B b = new B(param);
b.prop = a.prop;
return b;
}
}
Here I'm basically cloning the class. Is it possible to use the instance of A and simply add on the new prop, so I don't have to worry about manually cloning
I know this is probably possible by simply having the extra property be optional on A, but I don't think that's a good solution.
A a = new A();
B atoB = (B /* WITH NEW PARAM */) A
Upvotes: 2
Views: 63
Reputation: 12513
Java does not allow you to do that, and for very good reason. One of the key features of Java is its strong, static type system. Everything about a class definition (fields, methods, visibility, etc.) is decided when it is compiled and cannot be changed afterwards. When you create a class, for example
class A {
private int prop1;
private int prop2;
}
then anytime you create an instance with new A()
the instance is constructed exactly according to the specifications you gave in your code i.e. it is of type A
and has exactly two private fields, prop1
and prop2
, and nothing else (besides properties in Object
of course). If you create a class B
class B extends A {
private int extraProp;
}
You can create instances with new B()
that have the properties of A with the extra properties of B
. But even though B
extends A
, A
and B
are distinct types. You cannot take an existing instance of A
and "warp" into into an instance of class B
. Something like that could be possible in a language like JavaScript with its mutable prototypes, but in Java where class information is fixed at compile time, it is simply not possible.
All you can do is take the properties of an A
and create a new instance of B
with the same properties. But actually changing the class of an existing object to one of its sub-classes is impossible.
Upvotes: 3