Java Program on Bounded Generic
Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java
Program 1
package dataflair;
class MyClass<T extends Number>
{
T n;
MyClass(T n)
{
this.n=n;
}
public String toString()
{
return " "+n;
}
}
public class TestMain
{
public static void main(String[] args)
{
MyClass<Integer>M1=new MyClass<Integer>(500);
Short S=123;
MyClass<Short>M2=new MyClass<Short>(S);
Byte B=55;
MyClass<Byte>M5=new MyClass<Byte>(B);
// MyClass<String>M2=new MyClass<String>("Data Flair");
MyClass<Double>M3=new MyClass<Double>(50.67);
MyClass<Float>M4=new MyClass<Float>(50.45f);
// MyClass<Boolean>M4=new MyClass<Boolean>(true);
// MyClass<Character>M5=new MyClass<Character>('Y');
System.out.println(M1);
System.out.println(M2);
System.out.println(M3);
System.out.println(M4);
System.out.println(M4);
}
}Program 2
package dataflair;
class MyGen<T extends Number>
{
T ar[];
MyGen(T ar[])
{
this.ar=ar;
}
void sumofElements()
{
double s=0.0;
for(int i=0;i<ar.length;i++)
{
s=s+ar[i].doubleValue();
}
System.out.println("Sum of elements is: "+s);
}
}
public class TestMain1
{
public static void main(String[] args)
{
Integer I[]={10,20,30,40,50};
Double D[]={12.22,22.44,55.66,88.99};
Byte B[]={12,4,55,66,10};
String S[]={"a","b"};
MyGen<Integer>M1=new MyGen<Integer>(I);
MyGen<Double>M2=new MyGen<Double>(D);
System.out.println("Sum of Integer");
M1.sumofElements();
System.out.println("Sum of Double");
M2.sumofElements();
MyGen<Byte>M3=new MyGen<Byte>(B);
System.out.println("Sum of Byte");
M3.sumofElements();
}
} Did you know we work 24x7 to provide you best tutorials
Please encourage us - write a review on Google

