Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Gen<T> {
- T ob; // declare an object of type T
- // Pass the constructor a reference to
- // an object of type T.
- Gen(T o) {
- ob = o;
- }
- // Return ob.
- T getob() {
- return ob;
- }
- // Show type of T.
- void showType() {
- System.out.println("Type of T is " +
- ob.getClass().getName());
- }
- }
- // Demonstrate the generic class.
- class GenDemo {
- public static void main(String args[]) {
- // Create a Gen reference for Integers.
- Gen<Integer> iOb;
- // Create a Gen<Integer> object and assign its
- // reference to iOb. Notice the use of autoboxing
- // to encapsulate the value 88 within an Integer object.
- iOb = new Gen<Integer>(88);
- // Show the type of data used by iOb.
- iOb.showType();
- // Get the value in iOb. Notice that
- // no cast is needed.
- int v = iOb.getob();
- System.out.println("value: " + v);
- System.out.println();
- // Create a Gen object for Strings.
- Gen<String> strOb = new Gen<String>("Generics Test");
- // Show the type of data used by strOb.
- strOb.showType();
- // Get the value of strOb. Again, notice
- // that no cast is needed.
- String str = strOb.getob();
- System.out.println("value: " + str);
- }
- }
- _______________________________
- // A simple generic class with two type
- // parameters: T and V.
- class TwoGen<T, V> {
- T ob1;
- V ob2;
- // Pass the constructor a reference to
- // an object of type T.
- TwoGen(T o1, V o2) {
- ob1 = o1;
- ob2 = o2;
- }
- // Show types of T and V.
- void showTypes() {
- System.out.println("Type of T is " +
- ob1.getClass().getName());
- System.out.println("Type of V is " +
- ob2.getClass().getName());
- }
- T getob1() {
- return ob1;
- }
- V getob2() {
- return ob2;
- }
- }
- / Demonstrate TwoGen.
- class SimpGen {
- public static void main(String args[]) {
- TwoGen<Integer, String> tgObj =
- new TwoGen<Integer, String>(88, "Generics");
- // Show the types.
- tgObj.showTypes();
- // Obtain and show values.
- int v = tgObj.getob1();
- System.out.println("value: " + v);
- String str = tgObj.getob2();
- System.out.println("value: " + str);
- }
- }
- _______________________________
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement