Java Generic method overriding in a generic class.

Introduction

A method in a generic class can be overridden like any other method.


// Overriding a generic method in a generic class. 
class MyClass<T> {  
  T ob; // declare an object of type T  
    /* w  ww.  j av a 2  s.  co  m*/
  // Pass the constructor a reference to   
  // an object of type T.  
  public MyClass(T o) {  
    ob = o;  
  }  
  
  // Return ob.  
  public T getob() {  
    System.out.print("Gen's getob(): " ); 
    return ob;  
  }  
}  
 
class MySubclass<T> extends MyClass<T> { 
 
  MySubclass(T o) { 
    super(o); 
  } 
   
  // Override getob(). 
  public T getob() {  
    System.out.print("MySubclass's getob(): "); 
    return ob;  
  }  
} 
  
// Demonstrate generic method override. 
public class Main {  
  public static void main(String args[]) {  
    
    MyClass<Integer> iOb = new MyClass<Integer>(88); 
 
    MySubclass<Integer> iOb2 = new MySubclass<Integer>(99);  
   
    MySubclass<String> strOb2 = new MySubclass<String>("Generics Test");  
 
    System.out.println(iOb.getob()); 
    System.out.println(iOb2.getob()); 
    System.out.println(strOb2.getob()); 
  }  
}



PreviousNext

Related