Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.java.programmer > #14044

Re: generics

From Daniel Pitts <newsgroup.nospam@virtualinfinity.net>
Newsgroups comp.lang.java.programmer
Subject Re: generics
References <Ha6dnQN32-O6VgDSnZ2dnUVZ8q-dnZ2d@brightview.co.uk> <4f9dd125$0$293$14726298@news.sunsite.dk>
Message-ID <Erknr.175418$s82.33273@newsfe10.iad> (permalink)
Date 2012-04-29 16:48 -0700

Show all headers | View raw


On 4/29/12 4:39 PM, Arne Vajhøj wrote:
> On 4/29/2012 7:13 PM, Neil Morris wrote:
>> With the following code, what is the difference from one written with
>> Bounded Type Parameters? the code has type 'Number' with the 'add'
>> method using the 'Integer' type. How can I stop a subtype from being
>> passed to the 'add' method?
>>
>> public class Test<T> {
>> private T t;
>> public void add(T t) {
>> this.t = t;
>> }
>> public T get() {
>> return t;
>> }
>> public static void main(String[] args) {
>> Test<Number> test = new Test<Number>();
>> test.add(new Integer(10));
>> System.out.println(test.get());
>> }
>> }
>
> 1) Since Number is abstract then it will always be instances
> of subclasses that are passed.
>
> 2) The ability to pass subclasses or classes implementing interfaces
> is an essential part of OOP - preventing that is not good.
>
> 3) If you really want to block it then get the required type
> stored and make a very ugly test on type in add.
In the context of generics though, his question brings on new meaning. 
It also sounds like a homework assignment.

When declaring the "type" of the "test" variable in main, you can say 
"Test<? extends Number> test", which would mean that the "T" type in 
Test "is some unknown type that extends Number".  You will no longer be 
able to pass *anything* into add.

The converse operation is "Test<? super Number>" which means that T can 
"hold a Number", but not much else.

These are more useful when passing around collections of various sorts.

public void addStuff(Collection<? super Stuff> stuffs) {
    collection.add(new Stuff());
    collection.add(new SomethingThatExtendsStuff();
}

public void processStuff(Iterable<? extends Stuff> stuffs) {
    for (Stuff stuff: stuffs) {
       stuff.process();
    }
}

Hope this helps.

Back to comp.lang.java.programmer | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

generics Neil Morris <neil.morris4@googlemail.com> - 2012-04-30 00:13 +0100
  Re: generics Arne Vajhøj <arne@vajhoej.dk> - 2012-04-29 19:39 -0400
    Re: generics Daniel Pitts <newsgroup.nospam@virtualinfinity.net> - 2012-04-29 16:48 -0700
  Re: generics markspace <-@.> - 2012-04-29 17:48 -0700

csiph-web