Yes. By using an interface, a constant can be used by several classes. This helps keep the classes consistent.
Here is a tiny program that tests the classes.
If you want to run the program, copy and paste all the classes and
the interface to a file called Store.java
.
public class Store { public static void main ( String[] args ) { Goods gd = new Goods( "bubble bath", 1.40 ); Food fd = new Food ( "ox tails", 4.45, 1500 ); Book bk = new Book ( "Emma", 24.95, "Austin" ); Toy ty = new Toy ( "Legos", 54.45, 8 ); gd.display(); fd.display(); ty.display(); System.out.println("Tax is: " + ty.calculateTax() + "\n" ); bk.display(); System.out.println("Tax is: " + bk.calculateTax() + "\n" ); } }
The calculateTax()
method is only used with objects whose
class implements the interface
Here is a picture that shows the classes and their objects:
In the picture, clouds represent classes. Arrows with pointed head connect child classes to parent classes. The dotted rectangle represents the interface; a dotted arrow shows which classes implement it. Rectangles represent objects. Arrows with square head connect an object to its class.