Java OCA OCP Practice Question 1346

Question

Given the following code:

1. class MyClass { 
2.   float f; 
3.   MyClass() { 
4.     ???  // What goes here? 
5.   } 
6.   MyClass(float f) { 
7.     this.f = f; 
8.   } 
9. } 

What code at line 4 results in a class that compiles?

  • A. super();
  • B. this(1.23f);
  • C. this(1.23f); super();
  • D. super(1.23f); this(1.23f);


A, B.

Note

Option A legally invokes the superclass' no-args constructor.

The call is unnecessary, since the compiler inserts it in the absence of a call to any other superclass constructor.

Option B legally invokes the constructor at line 6.

C and D are illegal because in a constructor any call to super() or this() must be the first line of the constructor; so there's no room for both, in either order.




PreviousNext

Related