-1

Following code is not getting compiled and is giving below error upon compilation error at line 1:

Type mismatch: cannot convert from fourLegged to Dog1

From my understanding it should get compiled successfully and should not give any error.

   public class Test1 {

    public static void main(String[] args) {
        MyAnimal obj = new MyAnimal();
        Dog1 carDoor = obj.get()//Line 1;
    }

}

class MyAnimal<C extends BlackDog> extends AbstractAnimal<C> implements Animal1 {

}

abstract class AbstractAnimal<C extends FourLegged> {

    public C get() {
        return null;
    }

}

interface Animal1 {
    public Dog1 get();
}

interface FourLegged {
}

interface Dog1 extends FourLegged {
}

interface BlackDog extends Dog1 {
}

Can some one help me understand this behavior.

T-Bag
  • 10,916
  • 3
  • 54
  • 118
  • Side note: if you'd stick to the Java code conventions (which are there for a reason) it would be `FourLegged`. Also mind your naming in general, `MyAnimal` and `myCar` don't seem to fit very well and doing this on a larger scale might introduce hard to find bugs. – Thomas Jun 28 '17 at 08:39
  • Possible duplicate of [What is a raw type and why shouldn't we use it?](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) – Tom Jun 28 '17 at 08:45
  • @Tom- It is not duplicate please check again – T-Bag Jun 28 '17 at 08:46
  • 1
    It is. You're using a raw type and you already implicitly said (with your *"But why it is disabling generic type checking ?"* comment) that you don't know what a raw type is and what it causes. – Tom Jun 28 '17 at 08:47

1 Answers1

4

The problem is that MyAnimal myCar = new MyAnimal(); basically disables generic type checking and hence the code only knows that what get() returns is a FourLegged.

Changing it to MyAnimal<BlackDog> myCar = new MyAnimal<>(); (or even MyAnimal<?> myCar ..., see Seelenvirtuose's comment) should make it work. In both cases the compiler will then know that C in get() is (at least) an instance of BlackDog.

Thomas
  • 87,414
  • 12
  • 119
  • 157