Pergunta

while trying to get a grasp of polymorphism and inheritance, I made a small program to demonstrate these topics. The program consists of a superclass 'Tree' and three subclasses 'Birch', 'Maple', and 'Oak'. Tree's constructor makes it so that all trees start off with a height of 20 and 200 leaves. In Tree I have an abstract method called grow().

Here's the code for Tree:

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

}

Here's the code in Birch for 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...");

}

However, when I call code to make an array of trees grow, none of their heights or number of leaves change. Here's the code I used to populate the array of trees (I did it manually):

ArrayList<Tree> treeArray = new ArrayList<Tree>();

    treeArray.add( new Oak());
    treeArray.add(new Birch());
    treeArray.add(new Maple());

And Here's the code I used to call grow:

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() +".");
    }

Clearly, the values in the superclass aren't being modified. Any help will be appreciated! Thanks!

Foi útil?

Solução

Change your code to :

int height = super.getHeight();
super.setHeight(++height); 

note that you don't need to call super.method(). as long as the method is protected (public even better) you can just simplify it to :

int height = getHeight();
setHeight(++height);

You only call super. if you implement the method again in your child class and want to specifically call the parent class, which usually can be seen in constructor calling parent constructor.

One more thing : your accessor need to be changed a bit just for pre-caution case. see code below. Usually your IDE should support auto generation of accessor.

    public int getHeight() {
    return height;
    }

    public void setHeight(int height) {
    this.height = height;

    }

Outras dicas

This code:

int height = super.getHeight();
super.setHeight(height++);

isn't going to change anything, because the increment of height will occur after the call to super.setHeight(). So you're just setting the height to its current value.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top