开发者

Java - generic type

开发者 https://www.devze.com 2023-03-12 22:02 出处:网络
For this question, we assume that is possible to extend the class String in java. In the next code: T getId ( ) ;

For this question, we assume that is possible to extend the class String in java. In the next code:

T getId ( ) ;
void setId (T t ) ;
}
public class Person implements Identifiable <String> { . . . }
public class Car implements Identifiable <Integer> { . . . }
public class UTFString extends String { . . . }
public class Tourist implements Identifiable <UTFString> { . . . }

Identifiable <Y> z ;
if ( . . . ) {
     z = new Person ( ) ;
} else {
    z = new Tourist ( ) ;
}
z.setId(new UTFString(…))

I was asked what is the correct type of Y. I know that the type of Y, should be: ? super UTF-STRING, meaning: Identifiable <? super UTF-STRING> z; But why? as I see it, Persron and Tourist implements the interf开发者_运维百科ace UTFSTRING, and for that it should be ? extends UTF-STRING. What I miss?


Person and Tourist implement Identifiable<String> and Identifiable<UTFString> - the same generic interface, but with different type parameters. The type parameters are String and UTFString. These two classes are both subclasses of String and superclasses of UTFString, so both ? extends String and ? super UTFString will be allowed. The difference between them is what you can do with z: with ? extends String, you may not call methods that take the generic type as a parameter; with ? super UTFString, you may not call methods that return the generic type. Since you call z.setId(), which seems to take the generic type as a parameter, this excludes ? extends String.


If z was Identifyable<UTFString>, then z = new Person(); should not compile, as Person does not extend Identifyable<UTFString>.

I should possibly note that the notion of a UTFString seems rather confused - Strings do not have an encoding in Java. (They are always in Unicode. The only thing that can have an encoding is a sequence of bytes.)


I think you asked why you should use ? super UTF-STRING instead of ? extends UTF-STRING. If this is the question you can also use a Identifiable when declaring z. Person and Tourist implement it so you can use it for both. Honestly I think that a Tourist should extend a Person, because all the Tourists are Persons (in lexical meaning) so I'd declare

public class Person implements Identifiable { . . . }

public class Tourist extends Person { . . . }

Person z = null; if ( . . . ) { z = new Person ( ) ; } else { z = new Tourist ( ) ; } z.setId(new UTFString(…))

0

精彩评论

暂无评论...
验证码 换一张
取 消