Given:
class Base {
// insert code here
}
public class Derived extends Base {
public static void main(String[] args) {
Derived obj = new Derived();
obj.setNum(3);
System.out.println("Square = " + obj.getNum() * obj.getNum());
}
}
Which two options, when inserted independently inside class Base, ensure that the class is being properly encapsulated and allow the program to execute and print the square of the number?
A.
private int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
B.
public int num;
protected public int getNum() {
return num;
}
protected public void setNum(int num) {
this.num = num;
}
C.
private int num;
public int getNum() {
return num;
}
private void setNum(int num) {
this.num = num;
}
D.
protected int num;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
E.
protected int num;
private int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
题解
选项 A,标准的封装作法。
选项 B,protected 和 public 不可以同时使用,会造成编译错误。
选项 C,应将 setNum 方法的可见度修饰字改为 public。
选项 D,标准的封装作法,支持不同套件下的字段继承。
选项 E,应将 getNum 方法的可见度修饰字改为 public。
