Affichage des articles dont le libellé est How To Create Your Own Generic Class In Java NetBeans. Afficher tous les articles
Affichage des articles dont le libellé est How To Create Your Own Generic Class In Java NetBeans. Afficher tous les articles
JAVA - How To Create A Generic Class In Java NetBeans

JAVA - How To Create A Generic Class In Java NetBeans

JAVA - How To Create Your Own Generic Class In Java NetBeans

                                                                                                                       

In This Java Code We Will See How To Create A Generic Class Example In Java Programming Language.

Source Code:

package javaapp;
public class Woirk {

    //create a generic class 

    public static class GenericClass<T,K>{
        //create two attribute
        //T and K are types now
        private T Tval;
        private K Kval;
        
        //create a constructor without parameters 
        public GenericClass(){
            this.Tval = null;
            this.Kval = null;
        }
        //create a constructor with parameters 
        public GenericClass(T tval, K kval){
            this.Tval = tval;
            this.Kval = kval;
        }
        
        //get the value from Tval
        public T getTVal(){
            return this.Tval;
        }
        
         //set a value to Tval
        public void setTVal(T t){
            this.Tval = t;
        }
             
         //get the value from Kval
        public K getKVal(){
            return this.Kval;
        }
        
        //set a value to Kval
        public void setKVal(K k){
            this.Kval = k;
        }
        
        public void printValues(){
            System.out.println(this.Tval+" - "+this.Kval);
        }

    }
    
    public static void main(String[] args){
       
        GenericClass<Integer,String> gc;
        gc = new GenericClass<Integer,String>();
        gc.printValues();
        gc = new GenericClass<Integer,String>(11111,"JAVA");
        gc.printValues();
        gc = new GenericClass<Integer,String>(22222,"CSHARP");
        gc.printValues();
        gc.setTVal(33333);
        gc.setKVal("PHP");
        System.out.println(gc.getTVal()+" - "+gc.getKVal());
    }
    

}

//////////OUTPUT:

null - null
11111 - JAVA
22222 - CSHARP

33333 - PHP