本文介紹了變量具有私有訪問(wèn)權(quán)限的處理方法,對(duì)大家解決問(wèn)題具有一定的參考價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧!
問(wèn)題描述
我試圖為矩形和橢圓創(chuàng)建一個(gè)抽象的Shape類(lèi)我給Shape提供的唯一抽象方法是Draw方法,但在我給它一個(gè)構(gòu)造函數(shù)和它給我的所有東西之后,它在Rectangle類(lèi)中給了我一個(gè)錯(cuò)誤,說(shuō)顏色和其他變量有私有訪問(wèn),下面是我的代碼:
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;
意味著它們只能從聲明它們的實(shí)際類(lèi)訪問(wèn)。您應(yīng)該創(chuàng)建適當(dāng)?shù)?code>get和set
方法并使用它們。您希望字段是public
或protected
,以便使用點(diǎn)符號(hào)來(lái)訪問(wèn)它們,但我認(rèn)為將它們保持私有并使用get
和set
是更好的設(shè)計(jì)。另請(qǐng)參閱In Java, difference between default, public, protected, and private,它解釋了字段的可見(jiàn)性。
這篇關(guān)于變量具有私有訪問(wèn)權(quán)限的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,