简体   繁体   中英

Add subclass objects to an ArrayList

I'm about a month into my BSc in Software, and we are working on this forest project where we have different type of trees (ashes and beeches) which grows in different pace. They are subclasses to the general class Tree.

My problem is now I'm asked to add two trees of each kind of tree (ash and beech) to an ArrayList – their int age and double height should all be different. I simply can't put my head around how this should be set up so any advices/hints/solutions is greatly appreciated.

Source for Tree

public class Tree{

public int age;
public double height;

public void growOneYear()
{
    age++;
}

public void show()
{
    System.out.println("Træet er " +age+ " år gammelt og " +height+ " meter højt.");
}
}

Source for Ash (almost identical to Beech)

public class Ash extends Tree {

public Ash()
{
    age = 1;
    height = 1.0;
}

public void growOneYear()
{
    super.growOneYear();
        if(height < 15){
            height = height*1.20;
        }
}

public void show()
{
    System.out.println("Ask: ");
    super.show();
}
}

Screenshot of the structure

Use inheritance.

Declare Ash and Beech objects using Tree class should allow you to add the Tree object to the trees collection.

Tree ash = new Ash();
Tree beech = new Beech();
ash.growOneYear();
beech.growOneYear();
trees.add(ash);
trees.add(beech);

Considering you're already subclassing Tree with the extends Tree in the class declaration, at this point all you need to do in order to store all Trees and subclasses of Tree s in a List of Tree s is basically create the list, and add the trees to the list.

public class Forest
{
    private List<Tree> trees;

    public Forest()
    {
        trees = new ArrayList<>(); //diamond syntax Java 7, ArrayList<Tree>() on Java 6
    }

    public void addTree(Tree tree)
    {
        trees.add(tree);
    }

    public void growTreesByOneYear()
    {
        for(Tree tree : trees)
        {
            tree.growOneYear();
        }

        //you can do trees.stream().forEach(x -> x.growOneYear()); on Java 8
    }

    public void showTrees()
    {
        for(Tree tree : trees)
        {
            tree.show();
        }
    }
}

public class MainClass
{
    public static void main(String[] args)
    {
        Forest forest = new Forest();
        Ash ashTree = new Ash();
        Beech beechTree = new Beech();
        forest.addTree(ashTree);
        forest.addTree(beechTree);
        forest.show();
        forest.growTreesByOneYear();
        forest.show();
    }
}

I hope that helps!

Oh, and for the trees - you could probably provide the age and height in a constructor parameter, and create them something like this:

Ash ash = new Ash(5, 1.5); //age, height

Which would use

public class Ash extends Tree
{
    public Ash(int age, double height)
    {
        this.age = age;
        this.height = height;
    }
}

Or to be honest, it's clearer like this:

public class Tree
{
    public Tree(int age, double height)
    {
        this.age = age;
        this.height = height;
    }
}

public class Ash extends Tree
{
    public Ash(int age, double height)
    {
        super(age, height);
    }
}

I enclose you some code for illustration; the "keywords" you should understand in this context in the comments are in capital letters.

My classes are with the PACKAGE access modifier (which is actually not written; different access modifiers are PUBLIC, PROTECTED & PRIVATE), because this allows me to have several classes in one source file.

I hope this helps and you can learn something from it. If I can help, don´t hesitate to ask.


import java.util.ArrayList;


class Forest {

    public ArrayList<Tree> trees = new ArrayList();

    public void initialize () {
        // create and add 3 ashes on 3 different ways
        Ash ash1 = new Ash(10,32.5);    
        Tree ash2 = new Ash(1,2.5); 
        this.trees.add(ash1);       // "this" references the current object, but 
        trees.add(ash2);            // as there is no local trees variable 
        trees.add(new Ash(3,12.0)); // defined the compilier picks the right one 
        trees.add(new Tree(1,1.0));
    }

    public static void main(String[] args) {
        Forest forest = new Forest();
        forest.initialize();
        for (Tree tree : forest.trees) {   // FOR EACH loop
            System.out.println(tree.getClass()+" Age: "+tree.age);  
        }
    }            
}


class Tree {
    public int age;
    public double height;
    public Tree(int age,double height) {    // CONSTRUCTOR - creates an the object
        this.age=age;           // "this" references the current object, so in 
        this.height=height;     // this case the MEMBER VARIABLE is assigned
    }                           // the PARAMETER value
}


class Ash extends Tree {
    public Ash(int age,double height) {
        super(age,height);      // calls the constructor of the SUPERCLASS (Tree
    }                           // in this case with the PARAMETERs
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM