Download Java Generics

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1
Generic Types in Java 5.0
Outline and Required Reading:
• Generics
(§ 2.5.2)
• Autboxing, Auto-Unboxing (§ 1.3)
CSE 2011, Fall 2017
Instructor: N. Vlajic
Software ‘Bugs’
2
‘Bugs’ – are unavoidable in any nontrivial software project
• some ‘bugs’ are easier to detect and deal with than others
• compile-time errors immediately tell us that something is wrong,
so we can fix the problem
• run-time errors do not surface immediately - they (may) appear
at a point in time far removed from the actual cause of the problem
Issues surrounding
type checking,
conversion and casting
are often causes
of run-time errors in Java.
Generics – Java 5.0 (Tiger) feature aimed to add stability to Java code
by making more bugs detectable at compile time!
• generics enable stronger type checks at compile time thus
allowing for an ‘early detection’ of potential problems
Type Conversion & Type Casting in Java
Example [ type conversion & type casting on primitive types ]
double
8
3
Type Conversion & Type Casting in Java (cont.)
Example [ type conversion & type casting on primitive types ]
Difference between assignment operation in primitive and reference
variables in Java:
4
Type Conversion & Type Casting in Java (cont.)
5
Example [ type conversion & type casting on primitive types ]
explicit type casting aka
narrowing conversion:
automatic non-explicit
type casting aka
widening conversion:
variable of larger capacity
is assigned to another
variable of smaller capacity
variable of smaller
capacity is be assigned to
another variable of bigger
capacity
64 bits
32 bits
https://www.tutorialspoint.com/compile_java_online.php
Type Conversion & Type Casting in Java (cont.)
6
Example [ type conversion & type casting on reference types ]
String colour;
String colour;
double maxVolume;
public class BigBucket {
private String colour;
public BigBucket(String c) {
this.colour = c; }
}
public class SmallBucket extends BigBucket {
private double maxVolume;
public SmallBucket(String c, double v) {
super(c);
this.maxVolume = v; }
}
Type Conversion & Type Casting in Java (cont.)
7
Example [ type conversion & type casting on reference types ]
String colour;
String colour;
double maxVolume;
BigBucket A;
SmallBucket B = new SmallBucket(..);
A = B;
…
String colour = A.colour;
SmallBucket B;
BigBucket A = new BigBucket(..);
B = A; cause of the problem!!!
…
String colour = B.colour;
double volume = B.maxVolume;
Conversion (Casting) in Java
8
Widening Conversion – an assignment x = y, if data type x is capable
of referring to a wide variety of types than just y
• e.g. x-type is a superclass of y-type
• Java permits all widening conversions
Obj variable has a ‘wide’
ability to refer to different
objects, besides those of
type String.
String s = new String (“widening”);
Object obj;
obj = s;
Narrowing Conversion – an assignment x = y, and x has a smaller ability
to refer to things than y
• e.g. x-type is a subclass of y-type
• by using a typecast, Java allows all narrowing
conversions; but, runtime errors might occur!
String s = new String (“narrowing”);
Object obj;
obj = s;
s = (String) obj;
9
Generics: Motivation
Example [ Simple Box Class – operates on objects of any type ]
The goal was to create a generic box/container class that could be used
in various types of applications.
public class Box {
private Object o;
Box
o
O
public void add(Object o) {
this.o = o; }
}
public Object get() {
return o; }
Should you need to restrict the contained type to something specific, your
only option is to specify the requirement in the documentation (i.e. comment).
10
Generics: Motivation (cont.)
Example [ Simple Box Class used to store an Integer ]
public class BoxDemo1 {
public static void main(String[] args) {
// ONLY place Integer objects into this box!
Box integerBox = new Box();
Box
o
integerBox.add(new Integer(10));
10
O
…
Integer someInteger = (Integer) integerBox.get();
System.out.println(someInteger);
}
}
Example of ‘narrowing conversion’.
Allowed at compile time, but not
always safe – may result in runtime
exceptions.
We know that the cast from Object to Integer is correct because we've
honored the "contract" specified in the comment. But, the compiler
knows nothing about this — it just trusts that our cast is correct.
11
Generics: Motivation (cont.)
public class BoxDemo2 {
public static void main(String[] args) {
// ONLY place Integer objects into this box!
Box integerBox = new Box();
// Imagine this is one part of a large application
// modified by another programmer.
// Note how the type is now String.
integerBox.add("10");
// ... and this is perhaps written
// by a 3rd programmer
Box
o
Integer someInteger = (Integer) integerBox.get();
System.out.println(someInteger);
}
}
run-time error:
Exception in thread "main"
java.lang.ClassCastException:
java.lang.String cannot be cast to java.lang.Integer
at BoxDemo2.main(BoxDemo2.java:6)
“10”
O
Generics: Motivation (cont.)
12
Example [ Improved Box Class – Generic Box Class. ]
/* Generic version of the Box class.
public class Box<T> {
private T t; // T stands for "Type“
public void add(T t) {
this.t = t; }
Type parameter used inside
the class. Does not have to be
T, can be any other ‘name’, e.g.
ItemType.
The name in the definition will
be replaced by an actual type
name when the class is used
to create objects …
public T get() {
return t; }
}
To instantiate this class, an actual class type must be used in place of T.
Box<Integer> integerBox = new Box<Integer>();
13
Generics: Motivation (cont.)
public class BoxDemo3 {
public static void main(String[] args) {
Box<Integer> integerBox = new Box<Integer>();
integerBox.add(“10”);
Integer someInteger = integerBox.get();
// no cast!
System.out.println(someInteger); } }
compile-time error:
BoxDemo3.java:5: add(java.lang.Integer) in Box<java.lang.Integer>
cannot be applied to (java.lang.String)
integerBox.add("10");
^
1 error
Autoboxing and Auto-Unboxing
Autoboxing
(Boxing Conversion)
– aka implicit casting - Java 5.0 (Tiger) feature – occurs
when a primitive value is converted to a corresponding
wrapper object
• wrapper class – allows a primitive value to be treated
as an object
Example 3 [ wrapper classes ]
Integer age = new Integer(40);
Auto-Unboxing – occurs when a wrapper object is converted to the
corresponding primitive type
14
Autoboxing (cont.)
15
Example 4 [ autoboxing / unboxing ]
Integer obj;
int num = 37;
obj = num;
// automatically creates an Integer object
Integer obj = new Integer(73);
int num ;
num = obj;
// automatically extracts the int value – unboxing!!!
Example 5 [ autoboxing ]
Integer i = new Integer(9);
Integer j = new Integer(13);
int k = 9 + 13;
// always OK
Integer l = i + j;
// error in versions prior to 5.0!, but OK now
Integer n = new Integer(i + j); // always OK,
// equivalent to the above line