Scope of Generic Method Type Parameters

Java-Scope of Generic Method Type Parameters

Scope of Generic Method Type Parameters

Generic method can appear in either a generic or nongeneric class. For example, the following program declares a generic class called Gen and a generic method within that class called showUV( ). The showUV( ) method has its own parameter type declaration that defines the type variable U and V. The scope of U and V is limited to the method showUV( ) and hides any definition of U and V in Gen class.

Program

Generic Methods

Program Source

class Gen<U, V> {

    private U u;
    private V v;

    Gen(U uu, V vv) {
        u = uu;
        v = vv;
    }

    void showGenUV() {

        System.out.println("Gen U : " + u.getClass().getName());
        System.out.println("Gen V : " + v.getClass().getName());
    }

    <U, V> void showUV(U u, V v) {

        System.out.println("U : " + u.getClass().getName());
        System.out.println("V : " + v.getClass().getName());
    }
}

public class Javaapp {

    public static void main(String[] args) {

        Gen<Float, Double> gobj = new Gen<Float, Double>(4.5f, 7.5);
        gobj.showGenUV();
        gobj.showUV(50, "Ten");
    }
}

Leave a Comment