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!
Tree?