同時試圖獲得多態性和繼承的把握,我做了一個小程序來演示這些主題。該計劃由一個超級「樹」和三個小類「樺樹」,「楓樹」和「橡樹」組成。樹的構造函數使得所有樹的起始高度爲20和200葉。在樹中我有一個叫做grow()的抽象方法。從子類訪問和修改超類的屬性?
這裏的代碼樹:
public abstract class Tree {
private int height;
private int numberOfLeaves;
public Tree()
{
height = 20;
numberOfLeaves = 200;
}
public Tree(int aheight, int anum)
{
height = aheight;
numberOfLeaves = anum;
}
public int getHeight()
{
return height;
}
public int getNumberOfLeaves()
{
return numberOfLeaves;
}
public void setNumberOfLeaves(int anum)
{
numberOfLeaves = anum;
}
public abstract String getType();
public void setHeight(int aheight)
{
height = aheight;
}
public abstract void grow();
}
下面是生長在樺木()的代碼。
public void grow()
{
int height = super.getHeight();
super.setHeight(height++);
int num = super.getNumberOfLeaves();
super.setNumberOfLeaves(num+=30);
System.out.println("The Birch is Growing...");
}
但是,當我調用代碼來增加樹木數組時,它們的高度或樹葉數量都不會改變。 這是我用來填充樹的數組的代碼(我手工做的):
ArrayList<Tree> treeArray = new ArrayList<Tree>();
treeArray.add(new Oak());
treeArray.add(new Birch());
treeArray.add(new Maple());
,這裏是我用來調用成長代碼:
for (Tree tree : treeArray)
{
tree.grow();
System.out.println("The " + tree.getType() + "'s height is " + tree.getHeight() + " and it's number of leaves is "+ tree.getNumberOfLeaves() +".");
}
顯然,在超值沒有被修改。任何幫助將不勝感激!謝謝!
你可以發佈'樹'的代碼嗎? –
儘管它仍然取決於如何編寫樹類,請嘗試super.setHeight(++ height); – Rudy
好的@ElliottFrisch,我發佈了代碼樹 –