I am working on a project where I create "products" that are made up of ObservableList "parts".
Main screen
I create a product and add a part to it. You can see here, I add part "Screwdriver" to product TESTPROD1.
Creating Product
Next, I create TESTPROD2 and add part "Wrench" to it.
Creating Second Product
Finally, I go back to modify the original product (TESTPROD1), which should only contain "Screwdriver", but it contains both "Screwdriver" and "Wrench".
Modify TESTPROD1
Here is where I am creating the product when the "Save" button is pressed.
private void addProductSaveHandler(ActionEvent event) throws IOException {
Product p = new Product(
Integer.parseInt(addProductIdTextField.getText()),
addProductNameTextField.getText(),
Double.parseDouble(addProductPriceTextField.getText()),
Integer.parseInt(addProductInvTextField.getText()),
Integer.parseInt(addProductMinTextField.getText()),
Integer.parseInt(addProductMaxTextField.getText())
);
Inventory.addProduct(p);
for (Part addedPs : tableSelectedParts){
//Inventory.lookupProduct(p.getId()).addAssociatedPart(addedPs);
Inventory.lookupProduct(Integer.parseInt(addProductIdTextField.getText())).addAssociatedPart(addedPs);
}
tableSelectedParts.clear();
//Return to main screen
stage = (Stage)((Button)event.getSource()).getScene().getWindow();
scene = FXMLLoader.load(getClass().getResource("/view/MainForm.fxml"));
stage.setScene(new Scene(scene));
stage.show();
}
#FXML
private void addPartHandler(ActionEvent event) {
tableSelectedParts.add(addProductAllPartsTable.getSelectionModel().getSelectedItem());
}
public class Inventory {
private static ObservableList<Part> allParts = FXCollections.observableArrayList();
private static ObservableList<Product> allProducts = FXCollections.observableArrayList();
public static void addPart(Part newPart){
allParts.add(newPart);
}
public static void addProduct(Product newProduct){
allProducts.add(newProduct);
}
public static Part lookupPart(int partId){
return allParts.get(partId);
}
public static Product lookupProduct(int productId){
int productLocation = 0;
for (int i = 0; i < allProducts.size(); i++){
if (allProducts.get(i).getId() == productId){
productLocation = i;
}
}
return allProducts.get(productLocation);
}
public static ObservableList<Product> lookupProduct(String productName){
ObservableList<Product> matchingProduct = FXCollections.observableArrayList();
for (int i = 0; i < allProducts.size(); i++){
if (allProducts.get(i).getName().contains(productName)){
matchingProduct.add(allProducts.get(i));
}
}
return matchingProduct;
}
}
public class Product {
private static ObservableList<Part> associatedParts = FXCollections.observableArrayList();
private int id;
private String name;
private double price;
private int stock;
private int min;
private int max;
public Product(int id, String name, double price, int stock, int min, int max) {
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
this.min = min;
this.max = max;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the price
*/
public double getPrice() {
return price;
}
/**
* #param price the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* #return the stock
*/
public int getStock() {
return stock;
}
/**
* #param stock the stock to set
*/
public void setStock(int stock) {
this.stock = stock;
}
/**
* #return the min
*/
public int getMin() {
return min;
}
/**
* #param min the min to set
*/
public void setMin(int min) {
this.min = min;
}
/**
* #return the max
*/
public int getMax() {
return max;
}
/**
* #param max the max to set
*/
public void setMax(int max) {
this.max = max;
}
public static void addAssociatedPart(Part part){
associatedParts.add(part);
}
public boolean deleteAssociatedPart(Part part){
associatedParts.remove(part);
//not sure about this below - come back later
return false;
}
public static ObservableList<Part> getAllAssociatedParts(){
return associatedParts;
}
}
For some reason, creating a new product overwrites the ObservableList of parts associated with the previous product. I've been trying to figure out why this is for hours. Any help would be appreciated.
Your class Product declares associatedParts as being static. This means there is only one list per JVM, rather than one list per product.
In other words: remove the static keyword and each product will have its own associated parts.
Related
Please bear with me with this.Follow through the whole code.I will be putting everything just to be clear:
And this is my json : you can format here
https://jsonformatter.curiousconcept.com/
[{"productLineItemId":5,"restaurantId":2,"productId":5,"catalogName":"Cold Drink","categoryName":"sprite","subCategoryName":"SPRITE ","productName":"SPRITE","price":20.0,"optionName":"no","optionValues":"200ML","veg":true,"spicy":false},{"productLineItemId":8,"restaurantId":2,"productId":5,"catalogName":"veg","categoryName":"south indian","subCategoryName":"rice","productName":"jeera Rice","price":888.0,"optionName":"notning","optionValues":"ooo","veg":true,"spicy":true},{"productLineItemId":100,"restaurantId":2,"productId":5,"catalogName":"non veg","categoryName":"south indian","subCategoryName":"hot briyani","productName":"briyani","price":9.0,"optionName":"plate","optionValues":"half","veg":true,"spicy":true}]
Now Here ,you can see inside that json we have 3 objects right now,which in future will be dynamic,means could be many number.So, my goal is to retrieve all those Json Objects and show them in a custom adaptor list.
Below these are my codes:
MainActivity.java
try {
httpClient2=new DefaultHttpClient();
StringBuilder stringBuilder2=new StringBuilder("xxxxxxxx");
httpPost2=new HttpPost(stringBuilder2.toString());
httpResponse2=httpClient2.execute(httpPost2);
code=httpResponse2.getStatusLine().getStatusCode();
httpPost2.setHeader(HTTP.CONTENT_TYPE,"application/json");
HttpEntity httpEntity2=httpResponse2.getEntity();
if(code<200 && code>=300){
Log.d("msg","Here <200 and >300");
}
else{
if(httpEntity2!=null){
cena= EntityUtils.toString(httpEntity2);
JSONArray jsonArray=new JSONArray(cena);
hashMapArrayList=new ArrayList<HashMap<String,String>>();
for(int i=0;i<jsonArray.length();i++) {
jsonObject = jsonArray.getJSONObject(i);
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("Price", jsonObject.getString("price"));
hashMap.put("CategoryName", jsonObject.getString("categoryName"));
hashMap.put("ProductName", jsonObject.getString("productName"));
hashMap.put("CatalogName", jsonObject.getString("catalogName"));
hashMapArrayList.add(hashMap);
}
Intent intent = new Intent(MainActivity.this, Checkout.class);
intent.putExtra("arrayhash",hashMapArrayList);
startActivity(intent);
Log.d("cena","got something here"+cena.toString());
}
//Checkout.java
listView=(ListView)findViewById(R.id.listView);
hashMapArrayList2=(ArrayList<HashMap<String,String>>) getIntent().getSerializableExtra("arrayhash");
price_a = new String[hashMapArrayList2.size()];
categoryName_b = new String[hashMapArrayList2.size()];
productName_c = new String[hashMapArrayList2.size()];
catalogName_d = new String[hashMapArrayList2.size()];
int i=0;
for(Map<String,String> item:hashMapArrayList2){
price_a[i]=item.get("Price");
categoryName_b[i]=item.get("CategoryName");
productName_c[i]=item.get("ProductName");
catalogName_d[i]=item.get("CatalogName");
i++;
}
customAdapter=new CustomAdapter(Checkout.this,price_a,categoryName_b,productName_c,catalogName_d);
listView.setAdapter(customAdapter);
//This is my Custom Adaptor
public CustomAdapter(Context context,String price[],String categoryName[],String productName[],String catalogName[]){
this.context=context;
this.price=price;
this.categoryName=categoryName;
this.productName=productName;
this.catalogName=catalogName;
}
#Override
public int getCount() {
return price.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
layoutInflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v=layoutInflater.inflate(R.layout.custom_row,null);
tv2=(TextView)v.findViewById(R.id.textView2);
tv3=(TextView)v.findViewById(R.id.textView3);
tv4=(TextView)v.findViewById(R.id.textView4);
tv5=(TextView)v.findViewById(R.id.textView5);
return v;
}
//So i Am getting output like this :
//Now You could see the problem,I have 3 json objects but I am getting only one which I am able to show.Could you show me where modificatiuons needs to be so that I could show all json objects(dynamic) in custom adapter.I hope you got the full understanding.And I am new to development and If I have done any mistakes then sorry,deeply appreciated.
After some modification suggested from comment section,I got these :
Duplicate
Just modify your logic as below
hashMapArrayList=new ArrayList<HashMap<String,String>>();
JSONArray jsonArray=new JSONArray(cena);
for(int i=0;i<jsonArray.length();i++) {
jsonObject = jsonArray.getJSONObject(i);
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("Price", jsonObject.getString("price"));
hashMap.put("CategoryName", jsonObject.getString("categoryName"));
hashMap.put("ProductName", jsonObject.getString("productName"));
hashMap.put("CatalogName", jsonObject.getString("catalogName"));
hashMapArrayList.add(hashMap);
}
Just move HashMap<String, String> hashMap inside loop and add this one by one in hashMapArrayList
Modified code .
Initialize ArrayList out of the for loop and inside the for loop add the HashMap into the ArrayList
hashMapArrayList=new ArrayList<HashMap<String,String>>();
JSONArray jsonArray=new JSONArray(cena);
for(int i=0;i<jsonArray.length();i++) {
jsonObject = jsonArray.getJSONObject(i);
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("Price", jsonObject.getString("price"));
hashMap.put("CategoryName", jsonObject.getString("categoryName"));
hashMap.put("ProductName", jsonObject.getString("productName"));
hashMap.put("CatalogName", jsonObject.getString("catalogName"));
hashMapArrayList.add(hashMap);
}
Use Gson for the Parsing
#Generated("org.jsonschema2pojo")
public class Example {
#SerializedName("productLineItemId")
#Expose
private Integer productLineItemId;
#SerializedName("restaurantId")
#Expose
private Integer restaurantId;
#SerializedName("productId")
#Expose
private Integer productId;
#SerializedName("catalogName")
#Expose
private String catalogName;
#SerializedName("categoryName")
#Expose
private String categoryName;
#SerializedName("subCategoryName")
#Expose
private String subCategoryName;
#SerializedName("productName")
#Expose
private String productName;
#SerializedName("price")
#Expose
private Double price;
#SerializedName("optionName")
#Expose
private String optionName;
#SerializedName("optionValues")
#Expose
private String optionValues;
#SerializedName("veg")
#Expose
private Boolean veg;
#SerializedName("spicy")
#Expose
private Boolean spicy;
/**
* #return The productLineItemId
*/
public Integer getProductLineItemId() {
return productLineItemId;
}
/**
* #param productLineItemId The productLineItemId
*/
public void setProductLineItemId(Integer productLineItemId) {
this.productLineItemId = productLineItemId;
}
/**
* #return The restaurantId
*/
public Integer getRestaurantId() {
return restaurantId;
}
/**
* #param restaurantId The restaurantId
*/
public void setRestaurantId(Integer restaurantId) {
this.restaurantId = restaurantId;
}
/**
* #return The productId
*/
public Integer getProductId() {
return productId;
}
/**
* #param productId The productId
*/
public void setProductId(Integer productId) {
this.productId = productId;
}
/**
* #return The catalogName
*/
public String getCatalogName() {
return catalogName;
}
/**
* #param catalogName The catalogName
*/
public void setCatalogName(String catalogName) {
this.catalogName = catalogName;
}
/**
* #return The categoryName
*/
public String getCategoryName() {
return categoryName;
}
/**
* #param categoryName The categoryName
*/
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
/**
* #return The subCategoryName
*/
public String getSubCategoryName() {
return subCategoryName;
}
/**
* #param subCategoryName The subCategoryName
*/
public void setSubCategoryName(String subCategoryName) {
this.subCategoryName = subCategoryName;
}
/**
* #return The productName
*/
public String getProductName() {
return productName;
}
/**
* #param productName The productName
*/
public void setProductName(String productName) {
this.productName = productName;
}
/**
* #return The price
*/
public Double getPrice() {
return price;
}
/**
* #param price The price
*/
public void setPrice(Double price) {
this.price = price;
}
/**
* #return The optionName
*/
public String getOptionName() {
return optionName;
}
/**
* #param optionName The optionName
*/
public void setOptionName(String optionName) {
this.optionName = optionName;
}
/**
* #return The optionValues
*/
public String getOptionValues() {
return optionValues;
}
/**
* #param optionValues The optionValues
*/
public void setOptionValues(String optionValues) {
this.optionValues = optionValues;
}
/**
* #return The veg
*/
public Boolean getVeg() {
return veg;
}
/**
* #param veg The veg
*/
public void setVeg(Boolean veg) {
this.veg = veg;
}
/**
* #return The spicy
*/
public Boolean getSpicy() {
return spicy;
}
/**
* #param spicy The spicy
*/
public void setSpicy(Boolean spicy) {
this.spicy = spicy;
}
}
Example exampleObj = new Example();
Gson gson = new Gson();
JsonArray jsonArray = new JsonArray(response.string);
exampleObj=gson.fromJson(response.string,Example.class);
Sorry if the title wasn't very clear.
anyways, I'm making a monopoly game and im currently working on the income tax space. I have an idea of how to make that, but what I'm stuck on is a method that is supposed to get the total value of all money, properties, etc.
Here's what i have so far:
public int getTotVal()
{
int tot = 0;
for (int i = 0; i < this.properties.size(); i++)
tot += this.properties.get(i).mortgage;
return tot;
}
The for loop is supposed to run through the ArrayList of properties, and for each property, add the mortgage value to the varialble "tot".
I know this isn't right, but how would i do it correctly?
EDIT
Player:
import java.util.ArrayList;
public class Player
{
private String name;
private String token;
public int wallet;
private ArrayList properties;
public Player(String name, String token, int wallet, Property prop)
{
this.name = name;
this.token = token;
this.wallet = wallet;
this.properties.add(prop);
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the token
*/
public String getToken() {
return token;
}
/**
* #param token the token to set
*/
public void setToken(String token) {
this.token = token;
}
/**
* #return the wallet
*/
public int getWallet() {
return wallet;
}
/**
* #param wallet the wallet to set
*/
public void setWallet(int wallet) {
this.wallet = wallet;
}
/**
* #return the properties
*/
public ArrayList getProperties() {
return properties;
}
/**
* #param properties the properties to set
*/
public void setProperties(ArrayList properties) {
this.properties = properties;
}
//add buy()
//add butProp()
//add pay()
//add payRent()
public void pay(int amount)
{
this.wallet -= amount;
}
public int getTotVal()
{
int tot = 0;
for (Property property : this.properties)
{
tot += property.mortgage;
}
return tot;
}
}
Property:
package monopolysrc;
import java.util.Scanner;
public class Property extends Space
{
private int value;
private boolean owned;
private int mortgage;
public Property(String fn,String ln, int val, int mortgage, boolean owned)
{
super(fn,ln);
val = value;
owned = false;
this.mortgage = mortgage;
}
/**
* #return the value
*/
public int getValue() {
return value;
}
/**
* #param value the value to set
*/
public void setValue(int value) {
this.value = value;
}
/**
* #return the owned
*/
public boolean isOwned() {
return owned;
}
/**
* #param owned the owned to set
*/
public void setOwned(boolean owned) {
this.owned = owned;
}
/**
* #return the mortgage
*/
public int getMortgage() {
return mortgage;
}
/**
* #param mortgage the mortgage to set
*/
public void setMortgage(int mortgage) {
this.mortgage = mortgage;
}
}
Try this:
public int getTotVal() {
int tot = 0;
for (int i = 0; i < this.properties.size(); i++)
tot += this.properties.get(i).mortgage;
return tot;
}
There's a neat way to loop over every element of a List:
for (Property property : this.properties) {
tot += property.mortgage;
}
I have created an application using Spring MVC 3, Hibernate and Ext Js 4. The problem is that when I start the application the data is not readed from the database.
BookController.java:
#Controller
public class BookController {
private BookService bookService;
#RequestMapping(value="/books/view.action")
public #ResponseBody Map<String,? extends Object> view(#RequestParam int start, #RequestParam int limit) throws Exception {
try{
List<Book> books = bookService.getBookList(start,limit);
int total = bookService.getTotalBooks();
return ExtJSReturn.mapOK(books, total);
} catch (Exception e) {
return ExtJSReturn.mapError("Error retrieving books from database.");
}
}
BookService.java:
#Service
public class BookService {
private BookDAO bookDAO;
/**
* Get all books
* #return
*/
#Transactional(readOnly=true)
public List<Book> getBookList(int start, int limit){
return bookDAO.getBooks(start, limit);
}
public int getTotalBooks(){
return bookDAO.getTotalBooks();
}
BookDAO.java:
#SuppressWarnings("unchecked")
public List<Book> getBooks(int start, int limit) {
DetachedCriteria criteria = DetachedCriteria.forClass(Book.class);
return hibernateTemplate.findByCriteria(criteria, start, limit);
}
public int getTotalBooks(){
return DataAccessUtils.intResult(hibernateTemplate.find("SELECT COUNT(*) FROM books"));
}
Book.java:
#JsonAutoDetect
#Entity
#Table(name="books")
public class Book {
#Id
#GeneratedValue
#Column(name="id")
private int id;
#Column(name="title", nullable=false)
private String title;
#Column(name="author", nullable=false)
private String author;
#Column(name="publisher", nullable=false)
private String publisher;
#Column(name="isbn", nullable=false)
private String isbn;
#Column(name="pages", nullable=false)
private int pages;
#Column(name="category", nullable=false)
private String category;
#Column(name="qty", nullable=false)
private int qty;
/**
* #return the title
*/
public String getTitle() {
return title;
}
/**
* #param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* #return the author
*/
public String getAuthor() {
return author;
}
/**
* #param author the author to set
*/
public void setAuthor(String author) {
this.author = author;
}
/**
* #return the publisher
*/
public String getPublisher() {
return publisher;
}
/**
* #param publisher the publisher to set
*/
public void setPublisher(String publisher) {
this.publisher = publisher;
}
/**
* #return the isbn
*/
public String getIsbn() {
return isbn;
}
/**
* #param isbn the isbn to set
*/
public void setIsbn(String isbn) {
this.isbn = isbn;
}
/**
* #return the pages
*/
public int getPages() {
return pages;
}
/**
* #param pages the pages to set
*/
public void setPages(int pages) {
this.pages = pages;
}
/**
* #return the category
*/
public String getCategory() {
return category;
}
/**
* #param category the category to set
*/
public void setCategory(String category) {
this.category = category;
}
/**
* #return the qty
*/
public int getQty() {
return qty;
}
/**
* #param qty the qty to set
*/
public void setQty(int qty) {
this.qty = qty;
}
/**
* #return the id
*/
public int getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(int id) {
this.id = id;
}
}
ExtJsReturn.java:
#Component
public class ExtJSReturn {
/**
* Generates modelMap to return in the modelAndView
* #param books
* #return
*/
public static Map<String,Object> mapOK(List<Book> books){
Map<String,Object> modelMap = new HashMap<String,Object>(3);
modelMap.put("total", books.size());
modelMap.put("data", books);
modelMap.put("success", true);
return modelMap;
}
/**
* Generates modelMap to return in the modelAndView
* #param books
* #return
*/
public static Map<String,Object> mapOK(List<Book> books, int total){
Map<String,Object> modelMap = new HashMap<String,Object>(3);
modelMap.put("total", total);
modelMap.put("data", books);
modelMap.put("success", true);
return modelMap;
}
/**
* Generates modelMap to return in the modelAndView in case
* of exception
* #param msg message
* #return
*/
public static Map<String,Object> mapError(String msg){
Map<String,Object> modelMap = new HashMap<String,Object>(2);
modelMap.put("message", msg);
modelMap.put("success", false);
return modelMap;
}
}
The error is raised from the controller: Error retrieving books from database.
Do you have any ideea what can be the problem?
See here the Console output: http://pastebin.com/jMQKS31P
FIXED!!!
https://stackoverflow.com/a/14447201/1564840
You're passing a SQL request, using tables and column names, to a method which expects an HQL request, using entities, mapped fields and associations. SQL and HQL are two different query languages.
The HQL query should be
select count(book.id) from Book book
If you don't know about HQL, then you really need to read the documentation. Using Hibernate without knowing HQL is like using JDBC without knowing SQL.
i'm new to java and I am having problems adding my array objects to my list. I have already checked the topics in this forum but can't find something similar to my problem.
I have already made a class called Item that will save information about an item to be sold, and it has 4 instance variables id, desc, cost, quantity. And then I have a Sales class which has my main method. Basically what I want to do is build an array of objects from my Item class and hard code my data(which I have already created, i'm not sure if I did it right though).
I have created an ArrayList and what I want to do now is add the 5 objects from the array that I created into the list.
This is my Item class
public class Item {
private String itemID;
private String desc;
private double cost;
private int quantity;
public Item() {
itemID="";
desc="";
cost=0;
quantity=0;
}
public Item(String id, String d, double c, int q) {
itemID = id;
desc = d;
cost = c;
quantity = q;
}
/**
* #return the itemID
*/
public String getItemID() {
return itemID;
}
/**
* #param itemID the itemID to set
*/
public void setItemID(String itemID) {
this.itemID = itemID;
}
/**
* #return the desc
*/
public String getDesc() {
return desc;
}
/**
* #param desc the desc to set
*/
public void setDesc(String desc) {
this.desc = desc;
}
/**
* #return the cost
*/
public double getCost() {
return cost;
}
/**
* #param cost the cost to set
*/
public void setCost(double cost) {
this.cost = cost;
}
/**
* #return the quantity
*/
public int getQuantity() {
return quantity;
}
/**
* #param quantity the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/* (non-Javadoc)
* #see java.lang.Object#toString()
*/
#Override
public String toString() {
return "Item [itemID=" + itemID + ", desc=" + desc + ", cost=" + cost
+ ", quantity=" + quantity + "]";
}
}
And my Sales class:
import java.util.*;
public class Sales {
/**
* #param args
*/
public static void main(String[] args) {
int i;
Item[] items = new Item[5];
for(i = 0; i < items.length; i++)
{
items[i]= new Item(); // create array
}
//hard-coded values of id, desc, cost, qty
items[0].setItemID("PN250");
items[1].setItemID("ER100");
items[2].setItemID("PP150");
items[3].setItemID("MK200");
items[4].setItemID("PN300");
items[0].setDesc("Pen");
items[1].setDesc("Eraser");
items[2].setDesc("Paper");
items[3].setDesc("Marker");
items[4].setDesc("Pen");
items[0].setCost(1.50);
items[1].setCost(1.25);
items[2].setCost(3.75);
items[3].setCost(2.50);
items[4].setCost(2.25);
items[0].setQuantity(0);
items[1].setQuantity(175);
items[2].setQuantity(310);
items[3].setQuantity(75);
items[4].setQuantity(450);
double total = 0;
for(Item d : items)
{
System.out.print(d.getItemID());
System.out.print("\t" + d.getDesc());
System.out.print("\t" + d.getCost());
System.out.println("\t" + d.getQuantity());
}
List<Item> obj;
obj = new ArrayList<Item>();
}
}
You could add the array into your list with the following:
obj.addAll(Arrays.asList(items));
You can use:
for (i = 0; i < items.length; i++)
{
obj.add(items[i]);
}
but why not add the items as soon as they are created & populated?
instead of creating an array at the beginning of your function, create an arrayList and add objects to it using the put method.
Also, you should think of making your objects immutables and pass their attributes to their constructor instead of calling the setter for each attribute
I have an inventory program written to include an array and a method to calculate total cost for all inventory items entered. I now have to include a subclass that overrides the original to include "one unique feature". I created a new file named ItemDetails to set up for the subclasses of the original Item. I need to include one unique feature and calculate the value of the inventory and calculate a 5% restocking fee in this subclass. Do I just transfer some of the relevant lines into the other class? Or do I write some code twice? I don't know what to do next. Any help is useful. Thanks. This is what I have so far:
package inventory3;
public class ItemDetails extends Items
{
public static void override()
{
private String Name;
private double pNumber, Units, Price;
public ItemDetails()
{
}
}
}
This is the Item class file that it is supposed to override:
package inventory3;
import java.lang.Comparable;
public class Items implements Comparable
{
private String Name;
private double pNumber, Units, Price;
public Items()
{
Name = "";
pNumber = 0.0;
Units = 0.0;
Price = 0.0;
}
public int compareTo(Object item)
{
Items tmp = (Items) item;
return this.getName().compareTo(tmp.getName());
}
public Items(String productName, double productNumber, double unitsInStock, double unitPrice)
{
Name = productName;
pNumber = productNumber;
Units = unitsInStock;
Price = unitPrice;
}
//setter methods
public void setName(String n)
{
Name = n;
}
public void setpNumber(double no)
{
pNumber = no;
}
public void setUnits(double u)
{
Units = u;
}
public void setPrice(double p)
{
Price = p;
}
//getter methods
public String getName()
{
return Name;
}
public double getpNumber()
{
return pNumber;
}
public double getUnits()
{
return Units;
}
public double getPrice()
{
return Price;
}
public double calculateTotalPrice()
{
return (Units * Price);
}
public static double getCombinedCost(Items[] item)
{
double combined = 0;
for(int i =0; i < item.length; ++i)
{
combined = combined + item[i].calculateTotalPrice();
}
return combined;
}
}
You simply declare a method with the same signature as the method in the parent class. So yours would look like:
package inventory3;
public class ItemDetails extends Items {
private String Name;
private double pNumber, Units, Price;
public ItemDetails(String Name, double pNumber, double Units, double Price) {
this.Name = Name;
this.pNumber = pNumber;
this.Units = Units;
this.Price = Price;
}
// getters and setters....
// The #Override is optional, but recommended.
#Override
public double calculateTotalPrice() {
return Units * Price * 1.05; // From my understanding this is what you want to do
}
}