I would suggest you create an interface.
public interface PriceCheckable { public void checkPrice() }
Then your apple sells it
public class Apple extends Fruit implements PriceCheckable { int price; public Apple(String a, int b){ super(a); this.price = b; } public void checkPrice(){ if(this.price>2) System.out.print(" -- This apple is too expensive!"); else System.out.print(" -- This apple is cheap."); } }
Then in your loop you check for instance, listing, and access.
public void cartInventory(){ for(int i=0; i<cart.length; i++){ System.out.print("Item "+i+") "+cart[i].getClass()); if(cart[i] instanceof PriceCheckable){ PriceCheckable tmp = (PriceCheckable)cart[i]; tmp.checkPrice(); } System.out.println(); } }
You can then add a pricecheckable to any fruit, product, or thing you want.
Reading on java interfaces.
The bottom line is this: An interface is a contract between you and the code.
If an object implements an interface, this object must have at least those objects. Code will not compile if they are missing.
so if there is an interface
public interface Alphabet { public void A(); public int B(int b); public int C(); }
Any object that has this method is required to implement the three methods above as they see fit.
Sidenote
Usually the methods are followed by comments for the intended use, with additional additional restrictions and expectations, but one camera thinks more about those as suggestions.

Although, if you do not save these sentences, the code that expects certain restrictions will break.
Any class that has an interface can be passed to an object of type interface.
Alphabet alphabetInstance = (Alphabet)myobject;
You cannot access the normal methods of the myobject alphabetInstance object. The only methods available for the alphabetInstance instance are those described in the interface.
It allows you to access a method, but restricts access to other methods.
public void foo(MyObject myobject) { Alphabet alphabet = null; int worth = 10; if(MyObject instanceof Alphabet) { alphabet = (Alphabet)myobject; worth += alphabet.B(alphabet.C()); } myobject.handleWorth(worth); }
Either you do this, as above, have an explicit test if the object has a specific interface, and process the interface code in the if statement or, what I prefer, make a special method for this part only.
public void foo(MyObject myobject) { Alphabet alphabet = null; int worth = 10; if(myobject instanceof Alphabet) { worth += this.getAlphabetWorth(myobject); } myobject.handleWorth(worth); } public int getAlphabetWorth(Alphabet alphabet) { return alphabet.B(alphabet.C()); }
It may seem like it’s not an accidental job to make an additional method for it, but it may be the cases when you need to use more, and this saves you from copying and pasting code.