|
| 1 | +package s4j.java.chapter14; |
| 2 | + |
| 3 | +import s4j.java.chapter12.Customer; |
| 4 | +import s4j.java.chapter12.DiscountedCustomer; |
| 5 | +import s4j.java.chapter12.PricedItem; |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.util.List; |
| 8 | + |
| 9 | +public class Example { |
| 10 | + public static void main(String... args) { |
| 11 | + polymorphismInGenericLists(); |
| 12 | + exampleOfBoundedTypes(); |
| 13 | + assignmentRules(); |
| 14 | + } |
| 15 | + |
| 16 | + private static void polymorphismInGenericLists() { |
| 17 | + List<Customer> customers = new ArrayList<>(); |
| 18 | + // customers.add(new HockeyPuck()); // compiler failure |
| 19 | + |
| 20 | + Customer customerA = new Customer("Bob", "15 Fleetwood Mack Road"); |
| 21 | + Customer customerB = new DiscountedCustomer("Derick Jonar", "23 Woodland Way"); |
| 22 | + customerA.add(new PricedItem(10D)); |
| 23 | + customerB.add(new PricedItem(10D)); |
| 24 | + |
| 25 | + customers.add(customerA); |
| 26 | + customers.add(customerB); |
| 27 | + |
| 28 | + for (Customer customer : customers) { |
| 29 | + System.out.println(customer.getName() + " : " + customer.total()); |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + public static void exampleOfBoundedTypes() { |
| 34 | + |
| 35 | + // what's the difference between these two? |
| 36 | + |
| 37 | + Stack<Integer> a = new NumberStack<>(); |
| 38 | + a.push(12); |
| 39 | + Integer popA = a.pop(); |
| 40 | + |
| 41 | + Stack<Integer> b = new ListStack<>(); |
| 42 | + b.push(12); |
| 43 | + Integer popB = b.pop(); |
| 44 | + |
| 45 | + |
| 46 | + // Stack<String> b = new NumberStack<>(); // compiler failure |
| 47 | + } |
| 48 | + |
| 49 | + private static void assignmentRules() { |
| 50 | + |
| 51 | + // simple sub-type assignment |
| 52 | + |
| 53 | + A a = new A(); |
| 54 | + B b = new B(); |
| 55 | + a = b; |
| 56 | + // b = a; // compiler failure |
| 57 | + |
| 58 | + // not the same rules for generics |
| 59 | + List<B> listA = new ArrayList<>(); |
| 60 | + List<A> listB = new ArrayList<>(); |
| 61 | + // listA = listB; // compiler failure |
| 62 | + // listB = listA; // compiler failure |
| 63 | + } |
| 64 | + |
| 65 | + public static <A extends Comparable> List<A> sort(List<A> list) { |
| 66 | + list.sort((first, second) -> first.compareTo(second)); |
| 67 | + return list; |
| 68 | + } |
| 69 | + |
| 70 | + public static class NumberStack<T extends Number> extends ListStack<T> { } |
| 71 | + private static class HockeyPuck {} |
| 72 | + private static class A {} |
| 73 | + private static class B extends A {} |
| 74 | +} |
0 commit comments