I have a problem creating two classes that share heavy amount of code, with an attribute of the subclass meant to be a subclass of the attribute in the superclass. Let me provide a dummy example of what the root of the problem is:
public class A {
}
public class B extends A{
}
public class X{
A value;
}
public class Y extends X{
B value;
}
The shared code makes use of either A or B, depending on the situation. Converting value to protected and ignoring the problem did not work, during runtime in debugging of operations of class B, while in a shared method, I could see that Y.value was filled but X.value was not, eventually raising a NullPointerException. To face that issue I thought about adding a generic type T to the design thus:
public class A {
}
public class B extends A{
}
public class X<T extends A>{
T value;
}
public class Y extends X<B>{
}
which seems to work. Unfortunately however, there is a part of the code that tries to initialize the A or B, with a default constructor, which forces me to increase the complexity of the code with commands, like try catch handlders, that would otherwise not be needed. Another way of solving this situation was by introducing a parent class P:
public class A {
public class B extends A{
}
/**The abstract class has abstract the method that creates the T object
*/
public abstract class P<T extends A> {
}
public class X extends P<A>{
}
public class Y extends P<B>{
}
or creating an interface in the position, which would cause the requirement of the creation of a lot static methods that would need to be explicitly called in the implenting classes
Conclusively, I would like to ask whether there is a better solution than the ones I suggested, or which one of the above patterns seems the best to follow. FYI, I come from a Python background, where I had not faced such situations due to , well, duck typing.
Aucun commentaire:
Enregistrer un commentaire