I'm working through a Java book based on JDK 8. In the chapter about inheritance and generalisation the following example is shown:
class A {}
class B extends A {}
class C1 extends B { public void x1() {System.out.println("C1.x1");} }
class C2 extends B { public void x2() {System.out.println("C2.x2");} }
Then, some object variables are declared, all of type A
:
A obj1, obj2, obj3, obj4;
These variables are populated with instances of the four classes:
obj1 = new A();
obj2 = new B();
obj3 = new C1();
obj4 = new C2();
Now, obj3.x1()
doesn't work because obj3
is of type A
, and x1()
is not defined in A
. In the book, now one can declare a new variable obj5
of type C1
and assign to it the value of obj3
:
C1 obj5 = obj3; // then obj5.x1() should work
However on this line I get an Incompatible Types
compile error.
Is this different between SDK8 and 10? Or am I missing some error somewhere?
As a side note: casting such as in C1 obj5 = (C1) obj3
works.
A
object, whichobj3
is, is also aC1
object. Thus it is complaining and protecting you from a possible mistake. It is like if you are assuming that anAnimal
is also aDog
. But it could also be aCat
. However, when you are casting, you are telling the compile "Hey, it's fine, I know that it really is aC1
". – Zabuza Nov 28 '18 at 8:24