Generics
Generics makes it easy to catch runtime bugs such as wrong argument types. It tells the compiler to inform an error when there are wrong types, when a method call passes a string when it is expecting an integer.
Ex.
public class Vehicle{
private Object object;
public void start(Object object){
this.object = object;
}
public Object speed(){
return object;
}
public static void main (String[] args){
Vehicle v1 = new Vehicle(); created by different programmer
vi.start(“100”);
Integer speedofv = (Integer)v1.speed();
System.out.println(“speed of car is “ + speedofv);
}
} created by another programmer
This will result an error because it passes string where it expects an integer (this is at runtime not compile time).
Example on how to use generics:
public class Vehicle
private T t; //T stands for type
public void start(T t){
this.t = t;
}
public T speed(){
return t;
}
//we just replaced Object with T.
public static void main(String[] args){
Vehicle
v1.start(“100”);
Integer speedofv = v1.speed(); //no explicit casting
System.out.println(speedofv);
This will result an error in compile time having wrong types.
Type Convention:
T-type
N-Number
E-Element
V-Value
K-Key
You can also use generics in methods. The difference is it only accessed inside the method.
public<u>void direction(U u){
System.out.println(“T:” + t.getClass().getName());
System.out.println(“U:” + u.getClass().getName());
}
public static void main (String[] args){
Vehicle<integer>v1 = new Vehicle
v1.start(100);
v1.speed();
v1.direction(“North”);
}
prints out: T: java.lang.Integer
U:java.lang.String
to be continued...
No comments:
Post a Comment