Reputation: 25
my code is like this: i have two classes first class:
public class Box<E> {
E data1;
public Box(E data) {
this.data1 = data;
}
public E getData() {
return data1;
}
}
second class:
public class IntBox extends Box<Integer>{
Integer data;
public IntBox(Integer data) {
this.data = data;
}
public Integer getData() {
return data;
}
}
why doesn't this class extend from Box<E>
?
Upvotes: 0
Views: 78
Reputation: 22279
The later class extends from the first generic class. That should be no bigger issues with this example. Just make sure you call the constructor of the base class by super(data); in the IntBox constructor.
Upvotes: 0
Reputation: 285440
I wouldn't create a new class for this purpose since IntBox class doesn't add functionality to Box, but rather simply makes it more restrictive. Instead would simply declare Box to use Integer. i.e.,
public class Foo {
public static void main(String[] args) {
Box<Integer> intBox = new Box<Integer>(300);
System.out.println("data is: " + intBox.getData());
}
}
Upvotes: 1
Reputation: 40871
That won't compile.
Your second class should be:
public class IntBox extends Box<Integer>{
public IntBox(Integer data) {
super(data);
}
}
And then it will properly extend it and use Box's methods.
Upvotes: 1