In: Computer Science
JAVA
Copy the attached code into your IDE or an online compiler and test an additional type with the generic class. Submit your code and execution display.
JAVA
The test cases for Integer and String is given in the code.
Please add test cases for Character, Boolean and Double type etc.
// A Simple Java program to show working of user defined
// Generic classes
// We use < > to specify Parameter type
class Test<T>
{
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}
// Driver class to test above
public class Main
{
public static void main (String[] args)
{
// instance of Integer type
Test <Integer> iObj = new Test<Integer>(22);
System.out.println(iObj.getObject());
// instance of String type
Test <String> sObj =
new Test<String>("Print this string");
System.out.println(sObj.getObject());
}
}
// A Simple Java program to show working of user defined
// Generic classes
// We use < > to specify Parameter type
class Test < T >
{
// An object of type T is declared
T obj;
Test (T obj)
{
this.obj = obj;
} // constructor
public T getObject ()
{
return this.obj;
}
}
// Driver class to test above
public class Main
{
public static void main (String[]args)
{
// instance of Integer type
Test < Integer > iObj = new Test < Integer > (22);
System.out.println ("integer : "+iObj.getObject ());
// instance of String type
Test < String > sObj = new Test < String > ("Print this string");
System.out.println ("String :" +sObj.getObject ());
//instance of Character type
Test < Character > cObj = new Test < Character > ('C');
System.out.println ("Character : "+cObj.getObject ());
//instance of Double type
Test < Double > dObj = new Test < Double > (3.1454685222);
System.out.println ("Double : "+dObj.getObject ());
//instance of Boolean type
Test < Boolean > bObj = new Test < Boolean > (true);
System.out.println ("Boolean : "+bObj.getObject ());
//instance of Float type
Test < Float > fObj = new Test < Float > (1.23456f);
System.out.println ("Float : "+fObj.getObject ());
//instance of Byte type
Test < Byte > byObj = new Test < Byte > (Byte.MAX_VALUE);
System.out.println ("Byte : "+byObj.getObject ());
//instance of Long type
Test < Long > lObj = new Test < Long > (21000000000L);
System.out.println ("Long : "+lObj.getObject ());
}
}
-----------------------------------------------------------------------------------------------