variable has private access(变量具有私有访问权限)
                            本文介绍了变量具有私有访问权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
                        
                        问题描述
我试图为矩形和椭圆创建一个抽象的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;意味着它们只能从声明它们的实际类访问。您应该创建适当的get和set方法并使用它们。您希望字段是public或protected,以便使用点符号来访问它们,但我认为将它们保持私有并使用get和set是更好的设计。另请参阅In Java, difference between default, public, protected, and private,它解释了字段的可见性。
这篇关于变量具有私有访问权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
				 沃梦达教程
				
			本文标题为:变量具有私有访问权限
				
        
 
            
        基础教程推荐
             猜你喜欢
        
	     - 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
 - 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
 - Java Swing计时器未清除 2022-01-01
 - 在 Java 中创建日期的正确方法是什么? 2022-01-01
 - Java 实例变量在两个语句中声明和初始化 2022-01-01
 - 不推荐使用 Api 注释的描述 2022-01-01
 - 验证是否调用了所有 getter 方法 2022-01-01
 - 多个组件的复杂布局 2022-01-01
 - 大摇大摆的枚举 2022-01-01
 - 从 python 访问 JVM 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				