什么是“变量具有私有访问权限”的意思?我该如何修复它?

14

我试图为矩形和椭圆创建一个抽象形状类,我给形状类唯一的抽象方法是draw方法,但在我为其添加构造函数和其他内容后,代码中的矩形类出现错误,说颜色和其他变量在此处具有私有访问权限,这是我的代码:

public abstract class Shape{
        private int x, y, width, height;
        private Color color;
        public Shape(int x, int y, int width, int height, Color color){
            setXY(x, y);
            setSize(width, height);
            setColor(color);
        }

        public boolean setXY(int x, int y){
            this.x=x;
            this.y=y;
            return true;
        }

        public boolean setSize(int width, int height){
            this.width=width;
            this.height=height;
            return true;
        }

        public boolean setColor(Color color){
            if(color==null)
                return false;
            this.color=color;
            return true;
        }

        public abstract void draw(Graphics g);
    }

    class Rectangle extends Shape{
        public Rectangle(int x, int y, int width, int height, Color color){
            super(x, y, width, height, color);
        }

        public void draw(Graphics g){
            setColor(color);
            fillRect(x, y, width, height);
            setColor(Color.BLACK);
            drawRect(x, y, width, height);
        }
    }

    class Ellipse extends Shape{
        public Ellipse(int x, int y, int width, int height, Color color){
            super(x, y, width, height, color);
        }

        public void draw(Graphics g){
            g.setColor(color);
            g.fillOval(x, y, width, height);
            g.setColor(Color.BLACK);
            g.drawOval(x, y, width, height);
        }
    }
2个回答

3

private int x, y, width, height;表示它们只能从声明它们的实际类中访问。您应该创建适当的getset方法并使用它们。您希望这些字段是publicprotected,以使用点符号访问它们,但我认为将它们保持私有并使用getset是更好的设计。另请参见Java中default、public、protected和private之间的区别,其中解释了字段的可见性。


1
非常抱歉,我不太明白如何使用set和get方法,你能提供一个可视化的例子吗? - user3602628
在超类中添加所有私有字段的访问器方法,例如 public int getX(){return this.x;} 等等... 然后在子类(例如 Ellipse)中使用它们,如:g.fillOval(getX(), getY(), getWidth(), getHeight()); - Totò
所以如果我理解你的意思正确的话,你是说我需要在我的超类中添加get方法(因为我很确定我有setters),并将它们设置为返回true,然后只需将它们放在子类中替换所有括号中的变量即可? - user3602628
你需要在父类中添加get方法,并将它们设置为返回它们应该返回的内容(例如:public int getWidth(){return this.width;}public int getX(){return this.x;}),并使用它们来检索字段值,而不是直接访问字段。 - Totò
好的,我按照你说的做了,给所有的setter添加了get方法,并让它们返回true。我把这些get方法放在了子类中,就像你的例子一样,但现在它显示“getColor方法不能应用于给定的类型”。发生了什么事? - user3602628
抱歉,我不明白你的意思...为什么访问器方法必须返回truesetSomething不需要返回任何内容,而getSomeField必须返回someField。如果您可以使用最新更改更新问题中的代码,我们可能能够提供帮助。 - Totò

1
g.setColor(color);
g.fillOval(x, y, width, height);

所有这些字段都是父类的私有字段。
你无法从类外部访问私有字段,甚至无法从子类中访问。
你可以将该字段更改为受保护状态或提供getter方法以供子类调用。
因此,在Shape类中添加一个方法。
protected Color getColor(){  return color; }

然后你可以做

g.setColor(getColor());

在你的子类中。其他字段也是如此。

私有变量甚至在子类中也无法访问。您可以将该变量更改为受保护的(以便在子类和同一包中的类中访问),或者在子类中也使用getColor方法。 - Thinesh Ganeshalingam

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接