变量具有私有访问权限

use*_*628 5 java variables private subclass abstract

我正在尝试为矩形和椭圆形创建一个抽象形状类,我给形状赋予的唯一抽象方法是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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

Thi*_*ilo 1

g.setColor(color);
g.fillOval(x, y, width, height);
Run Code Online (Sandbox Code Playgroud)

所有这些字段都是父类私有的。

您不能从类外部访问私有字段,甚至不能从子类访问私有字段。

您可以将该字段更改为 protected 或提供 getter 供子类调用。

所以在Shape中添加一个方法

protected Color getColor(){  return color; }
Run Code Online (Sandbox Code Playgroud)

然后你可以做

g.setColor(getColor());
Run Code Online (Sandbox Code Playgroud)

在你的子类中。其他领域也一样。