Bei Instanz von in ein bestimmtes untergeordnetes Element umwandeln. Gibt es einen besseren Weg? [Duplikat]
Posted: 20 Jan 2025, 15:42
Übergeordnetes Element an Methode senden und dann AllBy ähnliche Produkte in der Datenbank finden.
Meine Datenbank hat 3 Tabellen. Produkt, Tischbier und Tischchips
Meine Datenbank hat 3 Tabellen. Produkt, Tischbier und Tischchips
Code: Select all
class Product {
String name;
String type;
int actualAmount;
int goalAmount;
}
class Beer extends Product {
int liters;
int percentage;
}
class Chips extends Product {
int weight;
String taste;
}
class ProductService {
private final ProductRepository repo;
//Send parent to method then getAll similar products by child variables.
public void foo(Product product) {
if (product instanceof Beer) {
Beer beer = (Beer) product;
List fromDb = repo.findAllByPercentage(beer.getPercentage());
}
else if (product instanceof Chips) {
Chips chips = (Chips) product;
List fromDb = repo.findAllByTaste(chips.getTaste());
}
}
}