JDK 1.5 Compiler not enforcing parameterized type in interface?

G

Guest

I'm starting to use the features of 1.5 and wondering why the following
isn't enforced by the compiler: I haven't been able to find an answer,
or alternative way of doing it:
I'm jusing JDK 1.5.0_7


If I declare a that a collection is of type Integer in an interface
such as:

public interface MyInterface {
public void doSomething(Collection<Integer> collection);
}


Why doesn't it complain if it is excluded from the implementing class?

public class MyClass implements MyInterface {
public void doSomething(Collection collection) {
collection.add(new String());
}
}

I would expect one of 2 compiler errors:
1. MyClass doesn't implement the interface correctly since the method
signatures are different.
2. String can't be added to collection of Integer.

I suspect it has to do with the rewrite from 'erasure' to remove
generics,
but is this a compiler bug, or should I be doing it a different way?

Thanks,
-CEC
 
T

Thomas Hawtin

public interface MyInterface {
public void doSomething(Collection<Integer> collection);
}


Why doesn't it complain if it is excluded from the implementing class?

public class MyClass implements MyInterface {
public void doSomething(Collection collection) {
collection.add(new String());
}
}

I would expect one of 2 compiler errors:
1. MyClass doesn't implement the interface correctly since the method
signatures are different.

As far as the JVM is concerned, both are methods called doSomething that
take a single Collection argument and return void. The signature is the
same.

The advantage of erasure is that if the base class had been updated to
use generics, the old derived class still works.
2. String can't be added to collection of Integer.

The static type is Collection, not Collection<Integer>.

When you compile the code, you should get a warning. Listen to compiler
warnings.

Tom Hawtin
 
S

Soren Kuula

Thomas said:
(e-mail address removed) wrote:

As Thomas said, because of backwards compatibility issues, you will only
get a warning if you implement with a class that does not use generics.

If, on the other hand, you do
you should get an error.
Søren
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,982
Messages
2,570,190
Members
46,740
Latest member
AdolphBig6

Latest Threads

Top