“Generics” is a special feature in java. It creates a generalized data member, classes and members. This can be used for any datatypes. So, it gives you the compile time type safety.
Eg:
class gene <G> {
G info;
public G getInfo(){
return info;
}
}
Where,
G is a parameter. The user replaces this with any datatypes (Primitive datatypes like int,String or user defined datatype).
Note: Different datatypes can be used without rewriting the
class.
Java program to implement generic class:
Generic class: sampleGene
Generic data member : T
Input method: input()
Output method: display()
Generic Objects : intsampleGene , strsampleGene
//Java Program
public class sampleGene<T> {
private T t;
public void
display(T t) {
this.t = t;
}
public T input() {
return t;
}
public static void
main(String[] args) {
sampleGene<Integer> intsampleGene = new sampleGene<>();
intsampleGene.display(456);
System.out.println("Integer Value: " + intsampleGene.input());
sampleGene<String> strsampleGene = new sampleGene<>();
strsampleGene.display("Have a nice day");
System.out.println("String Value: " + strsampleGene.input());
}
}
Output:
C:\raji\blog>javac sampleGene.java
C:\raji\blog>java sampleGene
Integer Value: 456
String Value: Have a nice day
Next Program implement the generic function.
Java Program to implement generic function:
This
program creates a generic function to process string and int array elements.
Generic function: display()- It gets the data as array elements
and prints it.
The array elements can be a int array or String.
//Program
public class genMethod{
public static
<T> void display(T[] inputA) {
for (T element
: inputA) {
System.out.print(element + " ");
}
System.out.println();
} public static void main(String[] args) {
Integer[]
intArray = {34, 42, 63, 74, 85};
String[]
strArray = {"Java","Generic","Programming"};
display(intArray);
display(strArray);
}
}
When you execute this program, you will get the below
output.
C:\raji\blog>javac genMethod.java
C:\raji\blog>java genMethod
34 42 63 74 85
Java Generic Programming
Note: you can try any type of array elements using this program.
No comments:
Post a Comment