Java OCA OCP Practice Question 1479

Question

Given the following code,

which of these constructors can be added to class MyClass without causing a compile time error?

class MyBaseClass { 
   int i; 
   public MyBaseClass (int x)  { this.i = x;  } 
} 
class MyClass extends MyBaseClass { 
   int j; 
   public MyClass (int x, int y)  { super (x);  this.j = y;  } 
} 

Select 2 options

  • A. MyClass ( ) { }
  • B. MyClass (int y ) { j = y; }
  • C. MyClass (int y ) { super (y*2 ); j = y; }
  • D. MyClass (int y ) { i = y; j = y*2; }
  • E. MyClass (int z ) { this (z, z); }


Correct Options are  : C E

Note

To construct an instance of a sub class, its super class needs need to be constructed first.

Since an instance can only be created via a constructor, some constructor of the super class has to be invoked.

Either you explicitly call it or the compiler will add super() as the first line of the sub class constructor.




PreviousNext

Related