tags:

views:

52

answers:

4

Hi I'm writing the reporting system and want to make end-user specify type if he extends my class.

class A <T extends C>
{...}

class B extends A // Compile error
{...}

class B extends A<D> // Compile error
{...}

class B extends A<C> // Success

Is that possible?

A: 

Yes, this will work if D is not of Type C

org.life.java
The main problem is with this part: class B extends A // Compile error{...} It allows to extend class A without specifying it's type.
joycollector
@joycollector, you want your programmer to allow this *your comment* or you don;t want to allow ?
org.life.java
I don't want to allow. =)
joycollector
+3  A: 
class B extends A // Compile error

No, for the sake of backwards compatibility, generics in Java are optional. You cannot force the programmer to use them. This will only generate a warning ("do not use raw types").

 class B extends A<D>  // compile error

If they do use generics, they have to be correct, though. In the case that D does not match the specification, this will be a compiler error.

Thilo
+1  A: 

@Thilo is right.

I'd just like to add that it is a bad idea to try to force people to use your classes in a particular way. They may have a good reason for using your code differently to the way that you intend. If you try to force a particular usage pattern, you may end up causing people to resort to horrible hacks, to fork your classes, or to simply go away and implement their own.

Stephen C
A: 

This is a job for your IDE or for external quality management tools (like Findbugs). You can configure Eclipse to treat unchecked warnings as error (and you can probably do the same with most IDEs). Or you can configure Findbugs to make your build fail in the same type of error.

Yes, those solutions leave the responsability to the user of your API to do the right thing, but it is most probably the right thing to do.

Guillaume