Spaces:
Running
Running
File size: 2,460 Bytes
a63c2ad |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 |
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);
}
|