-1

Usually, it is an error to pass a value of a supertype where a value of its subtype is expected.

EDIT : Take an example(though its a very weird one)

interface Testing{
    void printValue(TestClient cl);
}

class TestClient implements Testing{

    private String content;
    public TestClient(String content){
        this.content = content;
    }
    @Override
    public void printValue(TestClient cl) {
        // TODO Auto-generated method stub
        System.out.println((cl.content!=null ?cl.content :"Hello World"));
    }

}

public class Test{
    public static void main(String args[]) {
        Testing t = new TestClient("Hi Friends");
        Testing t1 = new TestClient("Hi Enemies");

        t1.printValue(t);  // generates error (The method printValue(TestClient) in the type Testing is not applicable for the arguments (Testing)
    }
}

Here , t1.printValue(t) method generates the error The method printValue(TestClient) in the type Testing is not applicable for the arguments (Testing)

But in Generics ,Every parameterized type is a subtype of the corresponding raw type, so a value of the parameterized type can be passed where a raw type is expected.

So, why does Java permit a value of a raw type to be passed where a parameterized type is expected— however, it flags this circumstance by generating an unchecked conversion warning.

Prateek
  • 12,014
  • 12
  • 60
  • 81
  • _Why Generics allow passing value of Supertype when subtype is expected?_ Let's say we have a dog, a cat and a horse. We want to call a method which accepts an animal as parameter. Aren't dogs, cats and horses animals? :) – BackSlash Sep 09 '13 at 13:46
  • Compile with "warnings as errors" turned on, and this will no longer be allowed. You should be doing this anyway. – Ben Sep 09 '13 at 13:49
  • @BackSlash see my edit, included some code. – Prateek Sep 09 '13 at 13:50
  • 2
    The example you provide does not show anything relevant to your question. – arjacsoh Sep 09 '13 at 13:52
  • 1
    Where are the generics in your code? – Mauren Sep 09 '13 at 13:55

2 Answers2

2

To allow backward compatibility with code/libraries written for Java 1.4 or prior before Generics where available. For details see What is the concept of erasure in generics in Java? and (possibly) http://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.8

Community
  • 1
  • 1
Patrick Huy
  • 975
  • 1
  • 8
  • 19
0

That's for backward compatibility. Think of a legacy method printList(List l) which is called like this:

List l = ...

printList(l);

Now you change the method to printList(List<?> l). If you wouldn't allow the call to accept a raw type (in which case type checks are disabled) you'd break the calling code.

That's one situation the Java developers had to face, thus it is allowed to pass raw types.

Another reason would be that the raw type version of the method would still be present at runtime due to type erasure.

Thomas
  • 87,414
  • 12
  • 119
  • 157