我的讲师告诉我,我的课堂上没有访问器和修改器方法,但我不知道他的意思,因为我确实包含了我的访问器和修改器方法。我能想到的两个问题是:1.My mutator 必须针对每个单独的变量,而不是一次针对所有变量。2.我的子类需要我的超类变量的访问器和修改器方法。我确实问过我的讲座,但他说自己去弄清楚,我没有包括 toString abstract class TwoD implements Shape{ //protected instance variables as the subclasses will use them protected int a; protected int b; protected int c; //default constructor public TwoD() {} //constructor for circle public TwoD(int a) { this.a = a; } //constructor for rectangle public TwoD(int a, int b) { this.a = a; this.b = b; } //constructor for triangle public TwoD(int a, int b, int c) { this.a = a; this.b = b; this.c = c; } //copy constructor public TwoD(TwoD td) { this (td.a, td.b, td.c); } //accessor methods to get variables public int getA() { return a; } public int getB() { return b; } public int getC() { return c; } //mutator methods to set variables public void setA(int a) { this.a = a; } public void setAB(int a, int b) { this.a = a; this.b = b; } public void setABC(int a, int b, int c) { this.a = a; this.b = b; this.c = c; }class Circle extends TwoD{ //default constructor public Circle() {} public Circle(int radius) { super(radius); } //method to calculate area of circle @Override public double area() { return Math.PI * a * a; } //method to get calculated area @Override public double getArea() { return area(); }
1 回答
白猪掌柜的
TA贡献1893条经验 获得超10个赞
访问器方法通常称为getter,而mutator 方法通常称为setter。
Java 世界中一种广泛使用的模式是:
将您的字段(实例变量)设为私有
private int a;
如果您需要访问器方法,请添加一个 getter
public int getA() {
return this.a;
}
如果您需要一个 mutator 方法,请添加一个 setter
public void setA(int a) {
this.a = a;
}
Accessor 和 mutator 方法几乎总是改变单个字段。
请注意,我和 Aaron Davis 一样,也不喜欢这种设计。由于子类只能添加功能,而不能删除或隐藏它,因此必须明智地选择哪个类扩展另一个类。一个例子是众所周知的正方形-长方形问题。
您还需要使用自描述名称。a,b并且c应该重命名为更好地描述这些变量代表的内容。
添加回答
举报
0/150
提交
取消
