Spaces:
Running
Running
| Although an object cannot be formed from an interface, an 'interface' can be used as a 'variable type'. | |
| Such a variable can store a REFERENCE to 'ANY OBJECT THAT IMPLEMENTS the INTERFACE'. | |
| However, note that ONLY OPERATIONS defined IN the INTERFACE can be called through such a variable. | |
| Let’s examine a method named ‘mostExpensive’, which takes a list of ‘Priced’ type objects as a parameter. | |
| The method finds the most expensive among these. | |
| Below is a refresher on the interface class ‘Priced’: | |
| interface Priced { | |
| int givePrice(); | |
| } | |
| The static method 'mostExpensive' now returns the element with the highest price from the given elements: | |
| public static Priced mostExpensive(ArrayList<Priced> list) { | |
| Priced mostExpensive = list.get(0); | |
| for (Priced product : list) { | |
| // 'product' object is from a class implementing the 'Priced' interface | |
| // which can use the 'givePrice' method from the interface | |
| if (product.givePrice() > mostExpensive.givePrice()) { | |
| mostExpensive = product; | |
| } | |
| } | |
| return mostExpensive; | |
| } | |
| The objects in the list can be of different types, the only REQUIREMENT is that EACH IMPLEMENTS the "Priced" interface. | |
| Examples include the classes "Fruit", "Car" and "MovieTicket": | |
| class Fruit implements Priced { | |
| private String name; | |
| public Fruit(String name) { | |
| this.name = name; | |
| } | |
| @Override | |
| public int givePrice() { | |
| return 10; | |
| } | |
| } | |
| class Car implements Priced { | |
| private String brand; | |
| private int price; | |
| public Car(String brand, int price) { | |
| this.brand = brand; | |
| this.price = price; | |
| } | |
| @Override | |
| public int givePrice() { | |
| return price; | |
| } | |
| } | |
| class MovieTicket implements Priced { | |
| private String movie; | |
| private int ageLimit; | |
| private int price; | |
| public MovieTicket(String movie, int ageLimit, int price) { | |
| this.movie = movie; | |
| this.ageLimit = ageLimit; | |
| this.price = price; | |
| } | |
| @Override | |
| public int givePrice() { | |
| return price; | |
| } | |
| } | |
| Let's create a few objects and call the method: | |
| public static void main(String[] args) { | |
| ArrayList<Priced> products = new ArrayList<>(); | |
| products.add(new Car("Mercedes", 15000)); | |
| products.add(new MovieTicket("Rambo 6", 21, 13)); | |
| products.add(new Fruit("Banana")); | |
| Priced mostExpensive = mostExpensive(products); | |
| } | |