Java OCA OCP Practice Question 1395

Question

Given the following three class declarations,

which sets of access modifiers can be inserted, in order, into the blank lines below that would allow all of the classes to compile? (Choose three.)

package mypkg; // w  ww  . ja  v a  2 s .  c o  m

public class Pet { 
   static int count; 
   long getCount() {return count;} 
} 
? 
package mypkg; 
public class Help { 
   private boolean needHelp() { return new Pet().count<10;} 
} 
? 
package sleep; 
public class Cat extends mypkg.Pet { 
   private boolean checkTime() { return getCount()>10;} 
} 
  • A. protected and package-private (blank)
  • B. public and public
  • C. package-private (blank) and protected
  • D. protected and protected
  • E. private and public
  • F. package-private (blank) and package-private (blank)


B, C, D.

Note

The count variable is accessed by a class in the same package; therefore, it requires package-private or less restrictive access (protected and public).

The getCount() method is accessed by a subclass in a different package; therefore, it requires protected or less restrictive access (public).

Options B, C, and D conform to these rules, making them the correct answer.

Options A and F cause the Cat class to fail to compile because the getCount() method is not accessible outside the package, even though Cat is a subclass of Pet.

Option E causes the Help class to fail to compile because the count variable is only visible within the Pet class.




PreviousNext

Related