I have the following classes:
class AbstractFruitData {
int size;
int weight;
}
class FruitData extends AbstractFruitData {
String name;
}
class AppleData extends FruitData {
String garden;
String getGarden() {
return garden;
}
}
class AbstractFruit<T extends AbstractFruitData> {
T data;
void setData(T data) {
this.data = data;
}
T getData() {
return data;
}
}
class Fruit<T extends FruitData> extends AbstractFruit<AbstractFruitData> {
String colour;
}
class Apple extends Fruit<AppleData> {
}
Then if I write the following code:
Apple apple = new Apple();
apple.setData(new AppleData());
apple.getData().getGarden(); <-- error
This is a mistake, because it datais a type AbstractFruitData. I can use it, but is it possible to write code in Java where the methods setDataor getDatawill only work with AppleData at compile time?
Second question: any design pattern, where can this class structure be replaced with better architecture?
source
share