D
David
To All,
Is there a way when I am creating my own generic class that I can define
the (for lack of a better term) highest super class allowed as the
generic?
To be more specific, for example, if you use define a Vector and don't
utilize the generics, an Object will be returned via the elementAt()
method. However, let's say I have written a MyObject class that extends
Object and I have a MyVector that extends Vector and I want to define
within MyVector that it only allows MyObject or other extensions of it
so that if a MyVector is instantiated with the generics definition, a
MyObject is returned, not an Object.
Is that clear?
Sniplets that may help or hinder......
class MyObject extends Object {
public void someMethod() { // do something }
}
class MyVector<V> extends Vector {
/* I want to force V to be an instance of MyObject */
public V elementAt(int index) { return super.elementAt(index); }
}
class Tester {
public static void main(String[] args) {
Vector v = new Vector();
v.add("A");
v.elementAt(0); // returns an Object.
Vector<String> v2 = new Vector<String>();
v.add("A");
v.elementAt(0); // returns a String.
MyVector mv = new MyVector();
mv.add(new MyObject());
/* The next line will fail because the default is to return an object
but I want it to be a MyObject. */
mv.elementAt(0).someMethod();
Is there a way when I am creating my own generic class that I can define
the (for lack of a better term) highest super class allowed as the
generic?
To be more specific, for example, if you use define a Vector and don't
utilize the generics, an Object will be returned via the elementAt()
method. However, let's say I have written a MyObject class that extends
Object and I have a MyVector that extends Vector and I want to define
within MyVector that it only allows MyObject or other extensions of it
so that if a MyVector is instantiated with the generics definition, a
MyObject is returned, not an Object.
Is that clear?
Sniplets that may help or hinder......
class MyObject extends Object {
public void someMethod() { // do something }
}
class MyVector<V> extends Vector {
/* I want to force V to be an instance of MyObject */
public V elementAt(int index) { return super.elementAt(index); }
}
class Tester {
public static void main(String[] args) {
Vector v = new Vector();
v.add("A");
v.elementAt(0); // returns an Object.
Vector<String> v2 = new Vector<String>();
v.add("A");
v.elementAt(0); // returns a String.
MyVector mv = new MyVector();
mv.add(new MyObject());
/* The next line will fail because the default is to return an object
but I want it to be a MyObject. */
mv.elementAt(0).someMethod();