Download presentation
Presentation is loading. Please wait.
1
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 1 L14 (Chapter 21) Generics 2
2
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 2 Bounded Generic Type public static void main(String[] args ) { Rectangle rectangle = new Rectangle(2, 2); Circle9 circle = new Circle9(2); System.out.println("Same area? " + equalArea(rectangle, circle)); } public static boolean equalArea(E object1, E object2) { return object1.findArea() == object2.findArea(); }
3
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 3 Raw Type and Backward Compatibility // raw type GenericStack stack = new GenericStack(); This is roughly equivalent to GenericStack stack = new GenericStack ();
4
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 4 Raw Type is Unsafe Max.max("Welcome", 23); // Max.java: Find a maximum object public class Max { /** Return the maximum between two objects */ public static Comparable max(Comparable o1, Comparable o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; } Runtime Error:
5
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 5 Make it Safe Max.max("Welcome", 23); // Max1.java: Find a maximum object public class Max1 { /** Return the maximum between two objects */ public static > E max(E o1, E o2) { if (o1.compareTo(o2) > 0) return o1; else return o2; }
6
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 6 Wildcards WildCardDemo1 Why wildcards are necessary? See this example. ? unbounded wildcard ? Extends T bounded wildcard ? Super T lower bound wildcard: WildCardDemo2WildCardDemo3
7
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 7 Generic Types and Wildcard Types
8
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved. 0-13-222158-6 8 Important Facts It is important to note that a generic class is shared by all its instances regardless of its actual generic type. GenericStack stack1 = new GenericStack (); GenericStack stack2 = new GenericStack (); Although GenericStack and GenericStack are two types, but there is only one class GenericStack loaded into the JVM.
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.