import tester.Tester; // some grocery items interface IItem { // is this the same IItem as other? boolean same(IItem x); // is this Coffee? boolean isCoffee(); // convert this to Coffee (if feasible) Coffee toCoffee(); // is this Tea? boolean isTea(); // convert this to Tea (if feasible) Tea toTea(); } class Coffee implements IItem { private String origin; private int price; Coffee(String origin, int price) { this.origin = origin; this.price = price; } public boolean isCoffee() { return true; } public boolean isTea() { return false; } public Coffee toCoffee() { return this; } public Tea toTea() { throw new RuntimeException("not a tea"); } public boolean same(IItem other) { return (other.isCoffee()) && other.toCoffee().same(this); } // is this the same Coffee as other? private boolean same(Coffee other) { return this.origin.equals(other.origin) && this.price == other.price; } } class Tea implements IItem { private String kind; private int price; Tea(String kind, int price) { this.kind = kind; this.price = price; } public boolean isTea() { return true; } public boolean isCoffee() { return false; } public Tea toTea() { return this; } public Coffee toCoffee() { throw new RuntimeException("not a coffee"); } public boolean same(IItem other) { return other.isTea() && other.toTea().same(this); } // is this the same Tea as other? private boolean same(Tea other) { return this.kind.equals(other.kind) && this.price == other.price; } } class Examples{ Examples(){} IItem tea1 = new Tea("Oolong", 200); IItem tea2 = new Tea("Oolong", 300); IItem coffee1 = new Tea("Kona", 300); IItem coffee2 = new Tea("Java", 200); boolean t1t2 = tea1.same(tea2); boolean c1c2 = coffee1.same(coffee2); boolean tc() {return tea1.same(coffee1);} boolean ct() {return coffee1.same(tea2);} public static void main(String[] argv){ Examples e = new Examples(); System.out.println(e.t1t2); System.out.println(e.c1c2); try{ System.out.println(e.tc()); } catch(RuntimeException ex){ System.out.println(ex.getMessage()); } try{ System.out.println(e.ct()); } catch(RuntimeException ex){ System.out.println(ex.getMessage()); } } }