Two SCJP questions
As an example for a generic class we will use a very simple container. A Basket can contain only one element.
Here the source code:
public class Basket<E> { private E element; public void setElement(E x) { element = x; } public E getElement() { return element; } }
We will store fruits in the baskets:
class Fruit { } class Apple extends Fruit { } class Orange extends Fruit { }
What would Java 1.5 do with the following source code?
Basket<Fruit> basket = new Basket<Fruit>(); // 1 basket.setElement(new Apple()); // 2 Apple apple = basket.getElement(); // 3
a)The source code is OK. Neither the compiler will complain, nor an exception during the runtime will be thrown.
b)Compile error in the line 2.
c)Compile error in the line 3.
Answer: c
The line 2 is ok. The line 3 however will cause a runtime error. The result type of the methode getElement of Basket is Fruit. We cannot assign a Fruit to a variable of the type Apple without a cast.
Question :
Let’s stay with our baskets. What do you think about the following source code?
Basket<Fruit> basket = new Basket<Fruit>(); basket.setElement(new Apple()); Orange orange = (Orange) basket.getElement();
a)e source code is OK. Neither the compiler will complain, nor an exception during the runtime will be thrown
b)mpile error in the line 2.
c)mpile error in the line 3.
d)ClassCastException will be thrown in the line 3.
Answer : d
Both Apples and Oranges are Fruits and can be inserted into a Basket. That is why the cast is necessary in the line 3.
During the runtime the JVM checks the cast in line 3 and throws a ClassCastException since an Apple is not a Orange.
There a lot of mock questions in this website
Comments(0)