I have an issue with a method not being visible to another class and I can't figure it out. I have a Shopping_Basket class that has a Merchandise list (Merchandise is a class). I'm trying to have the Merchandise list in the Shopping_basket class to reach a getItemCost method in the Merchandise class. However i get an error that the method is not visible... I can't figure out what's wrong:
public class Shopping_Basket {
private List<Merchandise> basket;
public List<Merchandise> getList() {
return basket;
}
public Shopping_Basket() {
basket = new ArrayList<Merchandise>();
}
public double getTotalCost() {
double j = 0;
for (int i = 0; i < this.getList().size(); i++){
j += basket.get(i).getItemCost();
}
return j;
}
Here's the Merchandise Class:
public class Merchandise {
private String item_name;
private int item_cost;
public Merchandise(String name, int cost) {
this.item_name = name;
this.item_cost = cost;
}
public String getItemName() {
return item_name;
}
public double getItemCost() {
return item_cost;
}
So error in the getTotalCost() method and it says the getItemCost() is not visible... help?
Your code is fine, and actually compiles and executes fine. See below and cross check if you did everything right (I have just added a main()
method in order to execute your code):
$ cat > Merchandise.java
public class Merchandise {
private String item_name;
private int item_cost;
public Merchandise(String name, int cost) {
this.item_name = name;
this.item_cost = cost;
}
public String getItemName() {
return item_name;
}
public double getItemCost() {
return item_cost;
}
}
$ cat > Shopping_Basket.java
import java.util.ArrayList;
import java.util.List;
public class Shopping_Basket {
private List<Merchandise> basket;
public List<Merchandise> getList() {
return basket;
}
public Shopping_Basket() {
basket = new ArrayList<Merchandise>();
}
public double getTotalCost() {
double j = 0;
for (int i = 0; i < this.getList().size(); i++) {
j += basket.get(i).getItemCost();
}
return j;
}
public static void main(String[] args) {
Shopping_Basket sb = new Shopping_Basket();
System.out.println(sb.getTotalCost());
}
}
$ javac Shopping_Basket.java
$ java Shopping_Basket
0.0
So, as I said and as you can see, the code is good. For the compiler, at least because there are a couple of things to point out:
Merchandise
, item_cost
is an int
, but getItemCost()
returns a double
Shopping_Basket
should be modified to something like ShoppingBasket