Register Now

Login

Lost Password

Enter your email to reset your password.

BY Author

Java – Generic Constructor

Similar to generic classes, we can create a generic constructor.

Java allows creating a generic constructor in a non-generic class.

Example

 class OOPs 
 {
     String name;
	
     OOPs(String name)
     {
         this.name = name;	
     }
	
     public void displayName() 
     {
         System.out.println(name);	
     }
 }

 class ProcedureOriented 
 {
     String name;
	
     ProcedureOriented(String name)
     {
         this.name = name;
     }
	
     public void displayName() 
     {
         System.out.println(name);	
     }
 }

 class GenericConsTest 
 {
     <T extends OOPs>GenericConsTest(T t) 
     {
         t.displayName();
     }
	
     public static void main(String args[])
     {
         OOPs n1 = new OOPs("Java");
         OOPs n2 = new OOPs("c#");
         ProcedureOriented p = new ProcedureOriented("C");
		
         GenericConsTest t1 = new GenericConsTest(n1);
         GenericConsTest t2 = new GenericConsTest(n2);
     //  GenericConsTest t3 = new GenericConsTest(p);
     }
 }

Output

Java
c#

If we removed comments at line,

GenericConsTest t3 = new GenericConsTest(p);

We will get compile time error because the argument p is not of OOP’s type or its child class.

 

Leave a reply