Search code examples
javainheritanceabstractcomposition

Composition relation using abstract classes-Java


I have a has a relationship between 2 classes: one is abstract class Region and the other is class KenKen. I have an ArrayList of type Region in class KenKen. How can I access the method addValue in Region class?

The classes are as follows:

Kenken:

public class KenKen {

private ArrayList<Region> regions;

public KenKen(String filename)throws FileNotFoundException{

  //constructor
  regions = new ArrayList<Region>();
  //regions.addValue(0);//   

}


public static void main(String[] args) throws FileNotFoundException{


       KenKen kenken1 = new KenKen("input.1.txt");


  }

}

Region:

public abstract class Region{

private int number = 0;
protected int target = 0;
protected ArrayList<Integer> values;

   public Region(int number , int target){

      this.number = number;
      this.target = target;

      //constructor
      values = new ArrayList<Integer>();

   }

   public void addValue(int val){

   }
   public abstract boolean verify();

   public String toString(){


   }

}

Solution

  • To access a member of an ArrayList you should use get(int index):

    Returns the element at the specified position in this list.

    So:

    regions.get(index).addValue(0);