2014-10-08 3 views
0

Я занимаюсь в этом году в моем программном обеспечении, и мы работаем над этим лесным проектом, где у нас есть разные типы деревьев (пепла и буки), которые растут в разном темпе. Они являются подклассами общего дерева классов.Добавить объекты подкласса в ArrayList

Моя проблема теперь меня попросили добавить два дерева каждого вида дерева (ясень и бук) в ArrayList - их int age и double height все должны быть разными. Я просто не могу сказать, как это должно быть настроено, поэтому приветствуются любые советы/подсказки/решения.

Источник 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."); 
} 
} 

Источник для Ash (почти идентичен бук)

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

+0

Кажется, вы хотите, дженерики и дженерики коллекции. Смотрите здесь: cs.nyu.edu/courses/spring12/CSCI-GA.3033-014/generics-tutorial.pdf –

ответ

1

Учитывая вы уже подклассов Tree с extends Tree в объявлении класса, в этот момент все, что вам нужно сделать для того, чтобы хранить все деревья и подклассы Tree с в List из Tree с является в основном создают список и добавьте деревья в список.

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

Надеюсь, что это поможет!

О, и для деревьев - вы, вероятно, может обеспечить возраст и высоту в качестве параметра конструктора, и создать им что-то вроде этого:

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

Что бы использовать

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

Или в быть честным, это яснее:

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); 
    } 
} 
+1

Большое вам спасибо!Вернемся к нему завтра и посмотрим, не наткнуться на любые последующие вопросы, но это имеет смысл. Опять же, очень ценится. – Aphex

1

Использование наследования.

Declare Ash и Beech объектов с помощью Tree класс позволит вам добавить Tree объект в trees коллекции.

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

Я привожу вам код для иллюстрации; «ключевые слова», которые вы должны понимать в этом контексте в комментариях, написаны заглавными буквами.

Мои классы с модификатором доступа PACKAGE (который на самом деле не написан, разные модификаторы доступа PUBLIC, PROTECTED & PRIVATE), потому что это позволяет мне иметь несколько классов в одном исходном файле.

Надеюсь, это поможет, и вы сможете чему-то научиться у него. Если я могу помочь, не стесняйтесь спрашивать.


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 
} 
Смежные вопросы