Java OCA OCP Practice Question 1038

Question

Which of the following statements can be inserted in the blank so that the code will compile successfully?

Choose all that apply

public class Animal {} 
public class Pet extends Animal {} 
public class Fish {} 
public class Main { 
  private Animal snake; 
  public void setAnimal(Animal snake) { this.snake = snake; } 
  public static void main(String[] args) { 
    new Main().setAnimal(  ___   ); 
  } /*ww  w .  ja  v  a  2s . c om*/
} 
  • A. new Pet()
  • B. new Fish()
  • C. new Animal()
  • D. new Object()
  • E. new String("Animal")
  • F. null


A, C, F.

Note

First off, Pet is a subclass of Animal, so option A can be used.

Fish is not defined as a subclass of Animal, so it cannot be used and option B is incorrect.

The class Animal is not marked as abstract, so it can be instantiated and passed, so option C is correct.

Next, Object is a superclass of Animal, not a subclass, so it also cannot be used and option D is incorrect.

The class String is unrelated in this example, so option E is incorrect.

Finally, a null value can always be passed as an object value, regardless of type, so option F is correct.




PreviousNext

Related