0

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;
}

}

2
  • could you post your Product class? Commented Nov 30, 2015 at 11:33
  • Hi k0ner, added the product class now. Thx for reply. Commented Nov 30, 2015 at 13:08

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.