CircAnalyzer
CircAnalyzer

Reputation: 704

JAVA Implementing Interfaces

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

Upvotes: 0

Views: 1477

Answers (1)

tombrown52
tombrown52

Reputation: 492

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.

Upvotes: 3

Related Questions