Before generics
List list = new ArrayList<>();
list.add(new Manager(2));
for(Object obj : list){
System.out.println(((Clerk)obj).display1());
}
// will lead to class cast exception.
Generics was derived for avoiding casting. I have written some code which gives a ClassCastException even after using generics.
class Employee{
int age;
Employee(int age){
this.age = age;
}
public void display(){
System.out.println("age:"+age);
}
}
class Manager extends Employee{
int age;
Manager(final int age) {
super(55);
this.age = age;
}
public void display(){
System.out.println("age:"+age);
}
}
class Clerk extends Employee{
int age;
Clerk(final int age) {
super(55);
this.age = age;
}
public void display1(){
System.out.println("age:"+age);
}
}
public static void main(String[] args) {
List<Manager> list1 = new ArrayList<>();
list1.add(new Manager(22));
test(list1);
}
private static void test(List<? extends Employee> list){
for(Employee employee1 : list){
((Clerk)employee1).display1();
}
}
In the method test
I have used lower bounded generic parameter. I have passed List of manager which is subclass of employee, but in test
I have provided implementation for another subclass of employee, class clerk which causes class cast exception.
Exception in thread "main" java.lang.ClassCastException: class generics.Manager cannot be cast to class generics.Clerk (generics.Manager and generics.Clerk are in unnamed module of loader 'app')
at generics.GenericsDemo.test(GenericsDemo.java:56)
at generics.GenericsDemo.main(GenericsDemo.java:50)
I am able to compile and execute code means Java supports this feature and i can use it in production. If I have no access to any caller method, any class nothing and I need to provide implementation of test method then how should I handle this exception?
Should I use instanceof
before typecasting? I want to understand technically how to handle and not fundamentally it is correct or incorrect, just how to handle exception.