Inheritance in java - something that i cannot understand

java

Solution

There are two distinct types involved here:

- type of the variable;

- type of the object referred to by the variable.

The type of the variable is independent of the type of the object it currently happens to be referring to—and vice versa, the type of the object doesn't depend on the type of the variable through which it is accessed. Therefore, as you assign an object to another variable of a different, its type is not influenced.

So,

- the type of variable `cd` is `C`;

- the type of the object referred to by it is `D`.

Problem

I have question regarding inheritance in Java that i cannot understand: I have these 2 classes: ``` public class C { public void foo(D d) { System.out.println("cd"); } } public class D extends C { public void foo(C c) { System.out.println("dc"); } public void foo(D d) { System.out.println("dd"); } } ``` And main: ``` public static void main(String[] args) { C cd = new D(); D dd = (D)cd; } ``` What is the type of each of `cd` and `dd` and why?

Original source