Reputation: 3895
I just wonder what usage the following code has:
public class Sub extends java.util.ArrayList<String> {...}
There is no any compiling restriction on the generic constraint java.util.ArrayList<String>
.
Upvotes: 0
Views: 1046
Reputation: 46415
You can extend class ArrayList
, but it is not something that you should normally do.
Only ever say "extends
" when you can truthfully say "this class IS-A that class.
"
Remember, Its not a good practise to extend the standard classes
Why not use like this ?
public class Sub {
List<String> s = new ArrayList<String>();
// ..
// ...
}
Upvotes: 1
Reputation: 120566
The compiler does place restrictions on other code based on the type parameter in this case.
This will compile
public class Sub extends java.util.ArrayList<String> {
void addTwice(String s) { this.add(s); this.add(s); }
}
but this will not
public class Sub extends java.util.ArrayList<String> {
void addTwice(Object x) { this.add(x); this.add(x); }
}
Upvotes: 3
Reputation: 11308
If you do that you can add to the basic functionality of an ArrayList
or even change its normal functionality.
For example, you can override the add()
method so that it will only add emails to the list.
Upvotes: 0
Reputation: 44808
Let's say you were making an index for a book, but you don't know how many indices you will need. You could make a class BookIndex extends ArrayList<String>
or if you want to get really picky: BookIndex extends ArrayList<IndexEntry>
.
/e1
Also, when a one Class extends a generic Class like ArrayList<String>
you can grab the String
out from the generic declaration, unlike if you had a class ArrayList<T>
. In ArrayList<T>
you would never be able to figure out what the T
is.
Upvotes: 1