变量具有私有访问权限 [英] variable has private access

查看:30
本文介绍了变量具有私有访问权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为矩形和椭圆创建一个抽象的Shape类我给Shape提供的唯一抽象方法是Draw方法,但在我给它一个构造函数和它给我的所有东西之后,它在Rectangle类中给了我一个错误,说颜色和其他变量有私有访问,下面是我的代码:

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);
        }
    }

推荐答案

private int x, y, width, height;意味着它们只能从声明它们的实际类访问。您应该创建适当的getset方法并使用它们。您希望字段是publicprotected,以便使用点符号来访问它们,但我认为将它们保持私有并使用getset是更好的设计。另请参阅In Java, difference between default, public, protected, and private,它解释了字段的可见性。

这篇关于变量具有私有访问权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆