Reputation: 35
I hope you can help me.
I'm working on a "Introduction to programming" Java-project for school, and have a little problem with inheritance.
I need to create methods for adding different products to an arraylist, that represents a very simple database. And so, i have an arraylist for cupcakes, one for bread etc.
How can I create a method in my superclass 'Product', that all the subclasses can inherit.
Right now the 'Add product' is implemented in every subclass, and looks something like this.
protected void addCakes() throws IllegalArgumentException {
System.out.println("Enter quantity to be added: ");
int n = scanner.nextInt();
if(n > 0) {
for(int i = 0; i < n; i++) {
cupcakedatabase.addCupcake(this);
}
} else {
throw new IllegalArgumentException("The amount has to be positive");
}
}
and the code in the cupcakeDB looks likes this:
private static ArrayList<Cupcake> cupcakes;
public CupcakeDB() {
cupcakes = new ArrayList<Cupcake>();
}
public void addCupcake(Cupcake cupcake) {
cupcakes.add(cupcake);
}
EDIT
This in my product class.
import java.util.Scanner;
public abstract class Product {
protected String name;
protected String flavor;
protected double price;
protected int quantity;
Scanner scanner = new Scanner(System.in);
public void createProduct(String name, String flavor, double price) {
this.name = name;
this.flavor = flavor;
this.price = price;
}
public void changePrice(double price) {
this.setPrice(price);
}
public void changeFlavor(String flavor) {
this.setFlavor(flavor);
}
public void setFlavor(String flavor) {
this.flavor = flavor;
}
public void setPrice(double price) {
this.price = price;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setName(String name) {
this.name = name;
}
public String getFlavor() {
return flavor;
}
public double getPrice() {
return price;
}
public String getName() {
return name;
}
public int getQuantity() {
return quantity;
}
}
Upvotes: 0
Views: 84
Reputation: 4207
you can try Something like,
class Product<T>{
ArrayList<T> list = new ArrayList<T>();
public void add(T t){
list.add(t);
}
public ArrayList<T> getMyAllProduct(){
return list;
}
}
Now Inherit this to your specific Product class and will get you it automatic.
Upvotes: 1