Java converts objects to unimplemented interfaces
I found the following problems in my study book and was a little confused:
Given the following code, which option, if used to replace / * insert code here * /, will enable the reference variable of roamable type to refer to the object? (select 1 option.)
interface Roamable{} class Phone {} class Tablet extends Phone implements Roamable { //INSERT CODE HERE }
Options include:
> Roamable var = new Phone(); > Roamable var = (roamable) telephone (); > Roamable var = (roamable) new phone (); > Because the interface roamable is not related to the phone class, it is a reference variable, and the roamable type cannot reference the object of the phone class
I think the correct option is 4, but it says it is 3
However, the phone does not implement the roamable interface, so you can't use it, can you?
Solution
The correct answer is 3: the compiler only sees that a phone is cast to roamable and the phone is not final. Therefore, it thinks that although the object being converted is called phone, it may be a subclass of the phone implementing roamable, so it will not issue compile time errors or warnings
According to JLS Chapter 5
5.5. 1. Reference type casting
The following code is compiled:
interface Roamable{} class Phone {} class Tablet extends Phone implements Roamable { Roamable var = (Roamable)new Phone(); // Compiles }