I am facing a downcast issue in my company software and I can't manage to find a workaround. (It's something put in place and I cannot change the whole conception)
I will try to give you the whole context with an example: Basically, we have 2 software components, let's say BrickHigh, BrickLow. BrickLow can use everything from BrickHigh but BrickHigh can't see Bricklow.
In BrickHigh there is an Animal class (dozens of attributes) with its DAO :
public class Animal .. {
//attributes...
}
In BrickLow I have created a Cat class (dozens of unmapped attributes aswell) which extends Animal.
public class Cat extends Animal {
//attributes
}
What was intended to do is to have a super class(Animal) with every mapped attribute. But I cannot use my animal class in my application because it would be too many changes since the whole app uses Cat.
But obviously, I cannot cast my Animal to Cat after getting it from the DAO since Java doesn't allow it, and I need every information from Animal.
Since my BrickHigh doesn't see my BrickLow, there are no such things as Animal animal = new Cat(); possible.
My first idea was to create a constructor in Cat that would take an Animal as parameter
public Cat(Animal a) {
super(a);
}
But what my constructor must be in my Animal class? It doesn't seem to work.
But what my constructor must be in my Animal class? It doesn't seem to work.
Something like this:
public Animal(Animal other) {
this.field1 = other.field1;
this.field2 = other.field2;
// etc
}
However, I think may be better off using the Object Factory pattern; i.e. have your DAO class take a parameter which is a factory object that can create Animal
instances. When you use the DAO (from BrickHigh) in code that uses the BrickLow APIs, you instantiate if with a factory that produces Cat
instances rather than Animal
instances.