0

I am working on an assignment in my JAVA class I'm stuck on. Basically I have a Product class as shown below. Then, I have a ProductDBImpl class that is to implement a ProductDB interface which is also shown below. The ProductDB is supposed to be a database of different products. Finally, the ProductDB interface is also shown below.

public class Product {
    private Integer id;
    private String name;
    private double price;
    private DeptCode dept; 

    public Product(String name, double price, DeptCode code){...}
    public Product(Integer id, String name, double price, DeptCode code) {...}
    public String getName() {...}
    public double getPrice() {...}
    public Integer getId() {...}
    public void setId(Integer id) {...}
    public DeptCode getDept() {...}
    public void setDept(DeptCode dept) {...}
    public void setName(String name) {...}
    public void setPrice(double price) {...}
    public String toString() {...}

}

import java.util.List;
public class ProductDBImpl implements ProductDB {

    public Product getProduct(int productId) {...}
    /**
     * Retrieve product by primary key
     * @param productId
     * @return null if not found
     */
    @Override
    public List<Product> getProductsByDept(DeptCode code) {...}
    /**
     * Retrieve all products in database
     * @return empty list if no products in database
     */
    @Override
    public void addProduct(Product product)
    /**
     * Update product in database with given information
     * @param p
     * @throws ProductNotFoundException if can't find given product by id
     */
    @Override
    public void updateProduct(Product product) throws ProductNotFoundException {...}
    /**
     * Remove product from database by product id
     * @param productId
     * @throws ProductNotFoundException if can't find given product by id
     */
    }
}

import java.util.List;

public interface ProductDB {

Product getProduct(int productId);
List<Product> getProductsByDept(DeptCode code);
List<Product> getAllProducts();
void addProduct(Product product) throws ProductAlreadyExistsException;
void updateProduct(Product product) throws ProductNotFoundException;
void deleteProduct(int productId) throws ProductNotFoundException;
}

I kind of understand that interfaces are sort of like a rule book that any class that tries using must follow. However, I am having a difficult time implementing the methods in the ProductDBImpl class. For example, when I try to implement the 'getProduct' method, I try the following but get errors:

    public Product getProduct(int productId) {
    // TODO Auto-generated method stub
    ProductDB someProduct = new ProductDBImpl();
    someProduct.getProduct();
}

I am using the getProduct() method because it is the method in the Product class that returns the Product ID.

Then, for the getProductsByDept() method I am not sure how to implement that because the Product class does not contain any of those methods, however there is a DeptCode class as the following:

public enum DeptCode {
     BOOK, COMPUTER, ELECTRONICS, DVD, SHOE
}

Am I supposed to implement it similar to the getProduct() method as follows:

    public List<Product> getProductsByDept(DeptCode code) {
    // TODO Auto-generated method stub
    ProductDB someProduct = new ProductDBImpl();
    return someProduct.getProductsByDept(code);
}

I guess I'm pretty confused on how to approach this whole assignment. Any help would be appreciated. Thanks!

After tombrown52's post things started making more sense. I started by adding the ArrayList for Products and implementing the getProduct method in ProductDBImpl class. However I am getting an error. Here is my code:

public List<Product> Products;

    @Override
public Product getProduct(int productId) {
    // TODO Auto-generated method stub
    for (int i = 0; i < Products.size(); i++)
    {
        if (Products.get(i).getId() == productId )
        {
            return Products.get(i);
        }
        else
        {
            return null;
        }
    }

The error I'm getting is that "This method must return a result of type Product'. I thought Products.get(i) was a Product?

Latest Edit: I am totally stumped. I have even tried the following code and still no luck:

// field declarations
    public ArrayList products = new ArrayList();



    @Override
    public Product getProduct(int productId)
    {
        // TODO Auto-generated method stub

        for (int i = 0; i < products.size(); i++)
        {
            Product p = (Product)products.get(i);
            if (p.getId() == productId )
            {
                return p;
            }
            else
            {
                return null;
            }
        }
    }
CircAnalyzer
  • 610
  • 1
  • 9
  • 29
  • Hi, I am not allowed to modify the code in ProductDB. Thanks. – CircAnalyzer Aug 14 '15 at 20:59
  • I don't see why this shouldn't work. Could you elaborate on the 'errors' you are getting? – Amit Assaraf Aug 14 '15 at 21:01
  • 1
    Gopgop is on the wrong track - the default visibility for interface methods is public in Java – David P. Caldwell Aug 14 '15 at 21:01
  • All the Java Interface methods, always will be public... :) Check this answer http://stackoverflow.com/questions/10169654/why-doesnt-java-allow-private-members-in-interface – Jorge E. Hernández Aug 14 '15 at 21:03
  • 1
    I think you have some kind of miss-conception. I will give you some kind of a start: `ProductDBImpl ` should store your data, so it should probably have a member (field) like `HashMap` or `ArrayList` to hold all products. – oshai Aug 14 '15 at 21:06
  • So am I implementing the methods incorrectly in ProductDBImpl? – CircAnalyzer Aug 14 '15 at 21:10
  • you should show us your error message and the code impacted if not already in your post – Bertrand Martel Aug 14 '15 at 21:14
  • How are you supposed to implement the product database -- what are your instructions regarding this? Can you just create and return dummy data from the methods or should you connect to an actual database? – Mick Mnemonic Aug 14 '15 at 21:19
  • The instructions were to basically provide the implementation of each of the methods in class ProductDBImpl. It is part of a larger package that contains the class I mentioned earlier plus other ones. However, I am confused on how to implement those methods. – CircAnalyzer Aug 14 '15 at 21:21
  • After your last update it looks like you're trying to call static methods on Products (unless there's more code you haven't shown), where what you should be doing is creating an instance of List and then call your methods on that instance. It might help to head over to the Java Tutorial and refresh on Classes, instances, methods etc, as it looks like you're missing a couple of key concepts : https://docs.oracle.com/javase/tutorial/ – Kevin Hooke Aug 15 '15 at 00:23
  • Based on tombrown52's pseudo code, there should be a field for List, which I call Products. Then are you suggesting that I instantiate it within the getProduct method by saying Products thisProduct = new List? – CircAnalyzer Aug 15 '15 at 18:49
  • @DeeTee You are right that `products.get(i)` will return a `Product`. However, the compiler must account for all possible branches of a method, and must ensure that each returns the correct type. The specific error you included doesn't mean that `products.get(i)` was wrong, but rather that the compiler found a branch that doesn't return anything. – tombrown52 Aug 17 '15 at 15:01
  • @tombrown52 do you think you can suggest a better way to populate the arraylist? I've tried several different ways and still no luck. – CircAnalyzer Aug 18 '15 at 00:36
  • @DeeTee When someone attempts to add a product to your database (via the `ProductDB.addProduct` method), you should add the product to the array list. Tip: The `ArrayList` has a method called `add`. – tombrown52 Aug 18 '15 at 15:38

1 Answers1

3

About Interfaces

As you said, an interface is a rule book that allows different parts of code to inter-operate together without having to know everything about each other. The "Impl" portion of ProductDBImpl is a naming convention that represents the fact that it's an implementation of the ProductDB interface.

But the interface ProductDB itself doesn't do anything. You will get an error if you try and create an instance of it using new ProductDB(). I.e. it is essentially a list of method names, and nothing else. (C++ calls interfaces virtual classes as in they don't really exist)

An implementation of an interface is a class that has all of the methods defined in the interface, so that if any code tries to call one of the interface's methods the program will know what to actually execute.

Your Assignment

Your assignment is to create a database that contains basic methods to Create, Read, Update, Delete products (see CRUD on wikipedia). In addition to basic reads, your database must be able to perform a specialized read that only returns products that matching certain criteria (e.g. find all products where product.dept == dept).

This database must conform to the ProductDBinterface. That is, the way you define your methods for the CRUD operations must be identical to the way they are defined in the interface.

How it relates to you

The database code itself will be written all by you. That sounds scarier than it actually is. You will need to store products in memory somewhere (using an array, List, or Map) and you will need to write code that can add items to it, remove items from it, or find specific items within it.

Here is some psuedo-code that may help:

class ProductDBImpl
   field "products" is an array of Products

   method "getProduct" returns Product, requires param "id" as string
      iterate over the "products" array:
         if a product has an id that matches the "id" parameter
            return the product.
      if no matching product is found:
         return null

   method "addProduct" returns nothing, requires param "product" as a Product
      iterate over the "products" array:
         if the product matches the "product" parameter
            throw an exception.
      if no matching product found:
         add the "product" parameter to the "products" array

Given that you have to create the database yourself, I think now you'll understand that there's nothing really special about the getProductsByDept(DeptCode) method. The method is as simple as iterating over the contents of the database, and including all matching Products in the list that will be returned.

tombrown52
  • 482
  • 4
  • 13