JavaBeans 对 OCA 方法命名约定的误解

Misunderstanding on JavaBeans naming convention for methods on OCA

我们目前正在对 OCA 证书进行相同的测试,今天我们 运行 遇到了一个小问题。 我会尽量保持简短:

Which are methods using JavaBeans naming conventions for accessors and mutators?

(Choose all that apply)
A. public boolean getCanSwim() { return canSwim;}
B. public boolean canSwim() { return numberWings;}
C. public int getNumWings() { return numberWings;}
D. public int numWings() { return numberWings;}
E. public void setCanSwim(boolean b) { canSwim = b;}

答案(由 OCA SE 8 指定):CE

我们讨论的是C点:

public int getNumWings() { return numberWings;}

我同事的观点是由于下面提到的规则是错误的。方法访问器必须是 getNumberWings 所以点 C 是错误的。我附上了 OCA 的 table 规则,它认为规则 5 是错误的。 PHOTO of Rules for JavaBeans naming convention on OCA SE 8 page 206

据我所知,方法的名称不必遵循 属性。 您对此有何看法?


OCA Oracle Certified Associate Java SE 8 程序员 I 学习指南考试 1Z0-808

我也试图在以下网站找到合适的答案:

Java来自 oracle 的 Beans 约定:http://download.oracle.com/otn-pub/jcp/7224-javabeans-1.01-fr-spec-oth-JSpec/beans.101.pdf?AuthParam=1484818426_7e07f5a35c14ebfbadb2c68798198d7e

JavaBeans 约定(Java 简而言之)

你的同事(我认为)认为

public int getNumWings() { return numberWings;}

违反了JavaBean,因为字段名称和属性名称不同。

规范不支持。 Java beans 约定(编纂 here)状态:

6.2.2. Properties

A bean defines a property p of type T if it has accessor methods that follow these patterns (if T is boolean, a special form of getter method is allowed):

Getter

    public T getP()

Boolean getter

    public boolean isP()

Setter

    public void setP(T)

Exceptions

Property accessor methods can throw any type of checked or unchecked exceptions

请注意,它没有说明保存 属性 值的(通常)private 字段的名称。事实上,该字段甚至可能不存在......如果 属性 值可以用其他方式表示。

关于 OCA,JavaBean 规则是:

所有 class 属性,即具有 getter 和 setter 的实例变量应遵循以下规则:

1) 实例变量始终设置为私有:

private boolean happy;

private String name;

2) mutator/setter 方法的 属性 标识符应始终以 'set' 开头,后跟 属性 的标识符,首字母大写:

public void setHappy(boolean happy){}

public void setName(String name){}

3) 布尔值 属性 的 accessor/getter 方法标识符应始终以 'is' 'get' 开头,后跟属性 首字母大写的标识符:

public boolean isHappy(){}

public boolean getHappy(){}

否则,如果 属性 不是布尔值,则 accessor/getter 方法的标识符应始终以 'get' 开头,后跟 属性 的标识符及其第一个字母大写:

public String getName(){}

4) 要注意的一个细微差别是,如果我们有一个布尔包装器 属性 而不是原始布尔值 属性:

private Boolean happy;

然后 getter 方法的标识符始终以 'get' 开头,后跟 属性 的标识符,首字母大写,并且 从不 'is' 因为我们返回的是对象而不是原始值:

public Boolean isHappy(){}

5) 以上规则仅适用于属性及其关联的 getter 和 setter 方法标识符,不适用于方法的任何局部变量,包括方法参数。