Java OCA OCP Practice Question 1929

Question

Given the following class declarations and declaration statements,

which assignment is legal at compile time?


// Class declarations:
interface MyInterface {}
class MyClass {}//  www .ja  v  a  2  s  .co m
class MyClass2 extends MyClass implements MyInterface {}
class MyClass3 implements MyInterface {}

// Declaration statements:
  MyClass b = new MyClass();
  MyClass2 c = new MyClass2();
  MyClass3 d = new MyClass3();

Select the one correct answer.

  • (a) c = d;
  • (b) d = c;
  • (c) MyInterface a = d;
  • (d) d = (MyClass3) c;
  • (e) c = b;


(c)

Note

Only MyInterface a = d is legal.

The reference value in d can be assigned to a, since MyClass3 implements MyInterface.

The statements c = d and d = c are illegal, since there is no sub type-super type relationship between MyClass2 and MyClass3.

Even though a cast is provided, the statement d = (MyClass3) c is illegal.

The object referred to by c cannot possibly be of type MyClass3, since MyClass3 is not a subclass of MyClass2.

The statement c = b is illegal, since assigning a reference value of a reference of type MyClass to a reference of type MyClass2 requires a cast.




PreviousNext

Related