Download presentation
Presentation is loading. Please wait.
Published byHugo Spencer Modified over 9 years ago
1
CSI 3125, Preliminaries, page 1 Generic Class & Generic methods
2
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.
3
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 ( ) 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).
4
CSI 3125, Preliminaries, page 4 Generic methods class G { 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 } }
5
CSI 3125, Preliminaries, page 5 Generic methods class G { 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); } }
6
CSI 3125, Preliminaries, page 6 Generic Class class test { 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 obj=new test ("ajith","popo"); test obj1=new test (10,20); obj.show(); obj1.show();} }
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.