java - 无访问器方法和修改器方法

标签 java

我的讲师告诉我,我的类里面没有访问器和更改器(mutator)方法,但我不知道他的意思,因为我确实包含了我的访问器和更改器(mutator)方法。

我能提出的第二个问题是:

1.我的更改器(mutator)必须针对每个单独的变量,而不是同时针对所有变量。

2.我的子类需要我的父类(super class)变量的访问器和修改器方法。

我确实问了我的讲座,但他说你自己去弄清楚,我没有包括 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();
    }

最佳答案

访问器方法通常称为 getter,修改器方法通常称为 setter。

Java 世界中广泛使用的模式是您

  • 将您的字段(实例变量)设置为私有(private)

    private int a;
    
  • 如果需要访问器方法,请添加 getter

    public int getA() {
        return this.a;
    }
    
  • 如果需要修改器方法,请添加一个 setter

    public void setA(int a) {
        this.a = a;
    }
    

访问器和修改器方法几乎总是更改单个字段

请注意,我,just like Aaron Davis ,也不喜欢这个设计。由于子类只能添加功能,而无法删除或隐藏它,因此必须明智地选择哪个类扩展另一个类。一个例子是众所周知的 squares-rectangles problem .

<小时/>

您还需要使用 self 描述性名称。 abc 应该重命名为更好地描述这些变量所代表的内容。

关于java - 无访问器方法和修改器方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53011421/

相关文章:

java - 编写java程序递归测试文件命名标准

java - 如何链接两个Jlist

java - 卡经销商java gui

java - 带有 MultiTenantConnectionProvider 的 Springboot Multi-Tenancy 总是抛出 org.apache.tomcat.jdbc.pool.PoolExhaustedException :

java - 这个 Haskell 函数的 Java 等价物是什么?

java - 组合多个 HTML CSS 以构建新页面

java - Spring Security 允许具有相同后缀的路径

java - 将奖励按钮按下限制为每小时一次

java - 无法在我的车辆交易程序中销售卡车和 1 个 JUnit 错误(缺少抽象方法)

java - 通过在 MySQL 中传递单个日期来检索带有 fromdate 和 todate 的记录