This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
This question is about assignment conversions, which do not require explicit casts. This example focuses on widening reference conversions. The JLS says, "A widening reference conversion exists from any type S to any type T, provided S is a subtype (�4.10) of T."
In this example:
The type of the reference "nc" is NewClass.
The type of the reference "o1" is Object.
The type of the reference "o2" is Interface.
The type of the reference "bc" is BaseClass.
The question is which of the variables (nc, o1, or o2) can we assign bc to without an explicit cast? In order to be a widening reference conversion, this means that bc must be a subtype of one of these.
Joined: Jan 29, 2005
Now I got it. So the correct answer is (2). This is also what I got when running the code. All the other options gave me a compilation error: incompatible types [ July 31, 2007: Message edited by: Joseph Sweet ]
Adding to what marc had said, just giving out a detailed explanation on the assignment.
Let's have a look at the classes or interfaces alone here.
The inheritance hierarchy becomes as follows
Now, consider your assignment options along with the objects you have created
Trying to assign the object of type "BaseClass" to an object of type "NewClass".
As it is in the reverse direction of inheritance, it is NOT allowed!.
Trying to assign an object of type "BaseClass" to an object of type "Object" ("O1").
Since the "BaseClass" does indirectly extend the "Object" class, it is allowed.
Before looking on the assignment, lets see what objects can the instance variable "o2" hold. As "o2" is of reference type "Interface I", it can ONLY hold the objects of class implementing the interface.
In case 3, you are trying to assign an object of type "BaseClass" to an object of type implementing the interface "I'. As "BaseClass" does NOT implement the Interface "I", its NOT allowed.
Getting back to your question asking which are allowed to compile without an error, only Option 2 wins the race!
Hope this clears. [ July 31, 2007: Message edited by: Raghavan Muthu ]