0

I have a project where I must use inner classes to declare types of food (created as 'Item' objects); for example, Pancake:

private class Pancake {          
    Item pan = new Item(5.50);                  
    public String toString() {   
                    
    }     
}      

As shown above the assignment given to me says each private inner class must override toString to return the name and price of the object. But, the test cases read what is returned from the toString method in the Item class (a different public class), which I currently have coded as:

@Override public String toString() {          
    return "" + " ($" + this.price + ")";     
} 

I do not know how to pass this toString method the name of the food type (i.e, Pancake). Item objects are created with a constructor that asssigns them a price, and that is all that is allowed. So I cannot use this.name or something like that to access the name of the food. How can I give this toString() method the name of the food (the private inner class, in a different class entirely)? No constructors are allowed to be implemented in the private classes. I've tried using this.getClass() but all that does is return a class type of Item, not the specific food class. Any help would be appreciated.

  • Possibly the food classes are intended to extend Item? – tgdavies Oct 11 '20 at 06:10
  • 1
    [Nested classes](https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html) have access to the private members of the enclosing (or outer) class. – Abra Oct 11 '20 at 06:13

0 Answers0