Advertisement
joseleonweb

Untitled

Apr 29th, 2021
688
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.34 KB | None | 0 0
  1. // A simple generic class
  2. // Here, T is a type parameter that
  3. // will be replaced by a real type
  4. // when an object of type Gen is created.
  5.  
  6. class Gen<T> {
  7.     T ob; // declare an object of type T
  8.     // Pass the constructor a reference to an object of type T.
  9.     Gen(T o) {
  10.         ob = o;
  11.     }
  12.    
  13.     // Return ob.
  14.     T getob() {
  15.         return ob;
  16.     }
  17.    
  18.     // Show type of T.
  19.     void showType() {
  20.         System.out.println("Type of T is " + ob.getClass().getName());
  21.     }
  22. }
  23.  
  24. // Demonstrate the generic class.
  25. public class GenDemo {
  26.     public static void main(String[] args) {
  27.         // Create a Gen reference for Integers.
  28.         Gen<Integer> iOb;
  29.        
  30.         // Create a Gen<Integer> object ans assign its reference to iOb.
  31.         // Notice the use of autoboxing to encapsulate the value 88
  32.         // whithin an Integer object.
  33.         iOb = new Gen<Integer>(88);
  34.        
  35.         // Show the type of data used by iOb.
  36.         iOb.showType();
  37.        
  38.         // Get the value in iOb.
  39.         // Notice that no cast is needed.
  40.         int v = iOb.getob();
  41.         System.out.println("value: " + v);
  42.        
  43.         System.out.println();
  44.        
  45.         // Create a Gen object for Strings.
  46.         Gen<String> strOb = new Gen<String>("Generics Test");
  47.        
  48.         // Show the type of data used by strOb.
  49.         strOb.showType();
  50.        
  51.         // Get the value of strOb.
  52.         // Again, notice that no cast is needed.
  53.         String str = strOb.getob();
  54.         System.out.println("value: " + str);
  55.     }
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement