MCA SEM – 1 Advance JAVA
PRACTICAL 1 (a)
Generic Classes
Program that demonstrates Generic Classes
Source Code
package Practical1;
class Shape<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
public class Practical1 {
public static void main(String[] args) {
Shape<Integer> intShape = new Shape<Integer>();
Shape<String> strShape = new Shape<String>();
Shape<Double> dblShape = new Shape<Double>();
[Link](new Integer(25));
[Link](new String("Generic Classes"));
[Link](new Double(65.431));
[Link]("Integer Value :"+[Link]());
[Link]("String Value :"+[Link]());
[Link]("double Value :"+[Link]());
}
Output
PRACTICAL 1 (b)
Gayatri Nandi
MCA SEM – 1 Advance JAVA
Generic Classes
Program that prints an array of different type using a single Generic method
Source Code
package practical1;
class GenericMethodEx2 {
// generic method printArray
public static < T> void printArray(T[] i) {
// Display array elements
for (T element : i) {
[Link](element);
}
[Link]();
}
}
class Practical1B {
public static void main(String args[]) {
// Create arrays of Integer, Double and Character
Integer[] intArray = {1, 2, 3, 4, 5};
Double[] doubleArray = {1.1, 2.2, 3.3, 4.4};
Character[] charArray = {'H', 'E', 'L', 'L', 'O'};
[Link]("Array integerArray contains:");
[Link](intArray); // pass an Integer array
[Link]("\nArray doubleArray contains:");
[Link](doubleArray); // pass a Double array
[Link]("\nArray characterArray contains:");
[Link](charArray); // pass a Character array
}
}
Output
Gayatri Nandi
MCA SEM – 1 Advance JAVA
Gayatri Nandi