Logic and data in the class

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?

+4
source share
1 answer

You must be able to convince the compiler to allow you access getGardenby connecting Tto AbstractFruit<T>in the declaration Fruit, for example:

class Fruit<T extends FruitData> extends AbstractFruit<T> {
    String colour; //                                  ^
}                  // Here is the change --------------+

, ( ideone).

, ; , , , , .

, , , , , .

+2

Source: https://habr.com/ru/post/1541810/


All Articles