Generics - Inheritannce
Generic Class Hierarchies
Generic classes can be part of a class hierarchy in just the same
way as a non-generic class. Thus, a generic class can act as a superclass or be
a subclass. The key difference between generic and non-generic hierarchies is
that in a generic hierarchy, any type arguments needed by a generic superclass
must be passed up the hierarchy by all subclasses. This is similar to the way
that constructor arguments must be passed up a hierarchy.
Syntax for creating and inheriting generic classes:
class super-class-name<type-param-list>
{
//…
}
class sub-class-name<type-param-list> extends
super-class-name<type-param-list>
{
//…
}
// Generic programming
// Inheritance and
constructors
// Method overriding
class GenA<T1>
{
public T1 x;
GenA(T1 v1)
{
x = v1;
}
public void fnDisplay()
{
System.out.println("x
= "+x);
}
}
class GenB<T1> extends GenA<T1>
{
T1 y;
GenB(T1 v1, T1 v2)
{
super(v1);
y = v2;
}
public void fnDisplay()
{
System.out.println("x
= "+x);
System.out.println("y
= "+y);
}
}
public class GenPgm10
{
public static void
main(String as[])
{
GenB<Double> g1
= new GenB<Double>(4.2,5.6);
g1.fnDisplay();
GenB<String> g2
= new GenB<String>("CSE","IT");
g2.fnDisplay();
}
}
// Generic programming
// Inheritance and
constructors
class GenA<T1 extends Number>
{
public T1 l, b;
double area;
GenA(T1 x, T1 y)
{
l = x;
b = y;
}
public void fnArea()
{
area =
l.doubleValue()*b.doubleValue();
System.out.println("Area
= "+area);
}
}
class GenV<T1 extends Number> extends GenA<T1>
{
T1 h;
double vol;
GenV(T1 x, T1 y, T1 z)
{
super(x, y);
h = z;
}
public <T1 extends
Number> void fnVol()
{
vol = l.doubleValue()*b.doubleValue()*h.doubleValue();
System.out.println("Volume
= "+vol);
}
}
public class GenPgm9
{
public static void
main(String as[])
{
GenV<Double> g1
= new GenV<Double>(4.2,5.6,6.1);
g1.fnArea();
g1.fnVol();
}
}
// Generic programming
// Find min value in
Arrays
class Gen<T1 extends
Comparable<T1>>
{
T1
x[];
Gen(T1
[]v1)
{
x
= v1;
}
public
void fnDisplay()
{
System.out.println("Array
elements");
for(int
i = 0;i<x.length;i++)
System.out.println(x[i]);
}
public
void fnFind()
{
T1
min = x[0];
for(int
i = 1;i<x.length;i++)
if(x[i].compareTo(min)
< 0 )
min
= x[i];
System.out.println("Minimum
value in array = "+min);
}
}
class GenPgm
{
public
static void main(String as[])
{
Integer
[] ia = {8,4,2,6};
Gen<Integer>
g1 = new Gen<Integer>(ia);
g1.fnDisplay();
g1.fnFind();
String
[]sa = {"cse", "it", "eee", "ece"};
Gen<String>
g2 = new Gen<String>(sa);
g2.fnDisplay();
g2.fnFind();
}
}
No comments:
Post a Comment
Don't be a silent reader...
Leave your comments...
Anu