Java OCA OCP Practice Question 1342

Question

What happens when you try to compile the following code and run the Horse application?

class Animal { /*w ww .j  a v a2s  . c o  m*/
     float weight; 
     Animal(float weight) { 
       this.weight = weight; 
     } 
} 

class Horse extends Animal {  
     public static void main(String[] args) { 
       Animal a = new Animal(222.2f); 
       Horse z = new Horse(); 
     } 
} 
  • A. Class Animal generates a compiler error.
  • B. Class Horse generates a compiler error.
  • C. The code compiles without error. The application throws an exception when the Animal constructor is called.
  • D. The code compiles without error. The application throws an exception when the Horse constructor is called.
  • E. The code compiles and runs without error.


B.

Note

Class Animal has no no-args constructor.

Class Horse has no constructor at all, so the compiler creates one that just calls the superclass' no-args constructor.

Since there is no such constructor, compilation fails.




PreviousNext

Related