Given the following Java code:

public class Hi {
  void m1() {}
  protected void m2() {}
}

class Lois extends Hi {
  // insert code here
}

Which four code fragments, inserted independently at line 7, will compile? (Choose four.)

A. private void m2() {} B. protected void m1() {} C. public void m1() {} D. pubic void m2() {} E. protected void m2() {} F. void m2() {} G. private void m1() {}

Explanation:

In this code, the Lois class extends the Hi class. We need to insert code snippets at line 7 that will compile successfully. Here are the four code fragments that will compile:

A. private void m2() {} This code snippet creates a private method m2() in the subclass. Private methods are not inherited, so they won't affect the parent class's methods.

C. public void m1() {} This code snippet creates a public method m1() in the subclass. Its access level is the same as the method in the parent class.

E. protected void m2() {} This code snippet creates a protected method m2() in the subclass. The access level is more specific than the method in the parent class.

F. void m2() {} This code snippet creates a method m2() with default access in the subclass. The access level is the same as the method in the parent class.

Therefore, the four code fragments that will compile are A. private void m2() {}, C. public void m1() {}, E. protected void m2() {}, and F. void m2() {}.

Java Inheritance: Which Methods Compile in a Subclass? (Multiple Choice)

原文地址: https://www.cveoy.top/t/topic/2yI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录