Wednesday, October 30, 2013

How implement bounded types (extend superclass) with generics?


As of now we have seen examples for only one type parameter. What happens in case we want to access group of objects comes from same family, means extending same super class? You can restrict the generics type parameter to a certain group of objects which extends same super class. You can achieve this my specifying extends at class definitions, look at the example, it gives you more comments to understand.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.java2novice.generics;
 
public class MyBoundedClassEx {
 
    public static void main(String a[]){
        //Creating object of sub class C and
        //passing it to BoundEx as a type parameter.
        BoundEx bec = new BoundEx(new C());
        bec.doRunTest();
        //Creating object of sub class B and
        //passing it to BoundEx as a type parameter.
        BoundEx beb = new BoundEx(new B());
        beb.doRunTest();
        //similarly passing super class A
        BoundEx bea = new BoundEx(new A());
        bea.doRunTest();
        //If you uncomment below code it will throw compiler error
        //becasue we restricted to only of type A and its sub classes.
        //BoundEx bes = new BoundEx(new String());
        //bea.doRunTest();
    }
}
/**
 * This class only accepts type parametes as any class
 * which extends class A or class A itself.
 * Passing any other type will cause compiler time error
 */
class BoundExextends A>{
     
    private T objRef;
     
    public BoundEx(T obj){
        this.objRef = obj;
    }
     
    public void doRunTest(){
        this.objRef.printClass();
    }
}
 
class A{
    public void printClass(){
        System.out.println("I am in super class A");
    }
}
 
class B extends A{
    public void printClass(){
        System.out.println("I am in sub class B");
    }
}
 
class C extends A{
    public void printClass(){
        System.out.println("I am in sub class C");
    }
}

Output:
I am in sub class C
I am in sub class B
I am in super class A

No comments: