csi 3125, preliminaries, page 1 generic class & generic methods
TRANSCRIPT
CSI 3125, Preliminaries, page 1
Generic Class & Generic methods
CSI 3125, Preliminaries, page 2
Generic Class & Generic methods• Advantage of Java Generics• There are mainly 3 advantages of generics. • 1) Type-safety : We can hold only a single type of
objects in generics. • 2) Type casting is not required: There is no need to
typecast the object.• 3) Compile-Time Checking: It is checked at compile
time so problem will not occur at runtime. • The good programming strategy says it is far better
to handle the problem at compile time than runtime.
CSI 3125, Preliminaries, page 3
Generic methods• write a single generic method declaration that can be called with
arguments of different types. • Based on the types of the arguments passed to the generic method, the
compiler handles each method call appropriately. • Following are the rules to define Generic Methods:• All generic method declarations have a type parameter section delimited
by angle brackets (< and >) that precedes the method's return type.• Each type parameter section contains one or more type parameters
separated by commas. • The type parameters can be used to declare the return type and act as
placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
• A generic method's body is declared like that of any other method. • Note that type parameters can represent only reference types, not
primitive types (like int, double and char).
CSI 3125, Preliminaries, page 4
Generic methods• class G • {• <T> void fun(T x)• {• System.out.println("value that passed to the function "+x);• }• public static void main(String a[])• {• G obj=new G();• obj.fun("ppp"); // call function with string argument• obj.fun(1); // cal function with int argument• obj.fun(2.5); // call fun with float argument• }•
• }
CSI 3125, Preliminaries, page 5
Generic methods• class G • {• <T> void swap(T x,T y)• {T t=x; x=y; y=t;• System.out.println(x +" "+y);}• public static void main(String a[])• {• G obj=new G();• obj.swap("ppp","aa");• obj.swap(1,5);• obj.swap(2.5,1.5);• }•
• }
CSI 3125, Preliminaries, page 6
Generic Class• class test <T>• {• T a,b;• test(T x,T y)• {a=x;b=y;}• void show()• {• System.out.println(a +" "+b);• }• public static void main(String a[])• {• test <String> obj=new test <String> ("ajith","popo");• test <Integer> obj1=new test <Integer> (10,20);• obj.show();• obj1.show();}• }