Question about setting variables of one class withnin another

edited October 2013 in Programming Questions

Hello!

I would like to execute a function of a class within another class (or rather set variables of a class within another class). I hope my code explains what I am searching for. Is something like that possible?

Thank you very much!

threeClass three;
fourClass[] four;

void setup()
{

  three =  new threeClass();
  four = new fourClass[10];
  for (int i = 0;i<four.length;i++) {
    four[i] = new fourClass();
  }
}


class oneClass
{
  int oneIndex;
  oneClass()
  {
    oneIndex = 0;
  }
  int getIndex()
  {
    return oneIndex;
  }
}


class twoClass
{
  oneClass[] one;
  int twoIndex;

  twoClass()
  {
    one = new oneClass[10];
    for (int i = 0;i<one.length;i++) {
      one[i] = new oneClass();
      twoIndex = one[i].getIndex();
    }
  }

  int getIndex()
  {
    return twoIndex;
  }
}


class threeClass
{
  twoClass[] two;
  int threeIndex;

  threeClass()
  {
    two = new twoClass[10];
    for (int i = 0;i<two.length;i++) {
      two[i] = new twoClass();
      threeIndex = two[i].getIndex();

      four[i].setIndex(threeIndex);        // this is my Problem
      // or four[i].fourIndex = threeIndex .. something like that
    }
  }
}


class fourClass
{

  int fourIndex;

  fourClass()
  {
    fourIndex = 0;
  }

  void setIndex(int newIndex) {

    fourIndex = newIndex;
  }
}

Comments

  • I don't understand what you are trying to achieve, but the code looks like it should function. Perhaps you believe that it doesn't work because you run the code inthreeClassbefore you create the array offourClass.

  • edited October 2013

    Okay, first to improve the readability of your code use the following convention:

    • Use a uppercase names for classes
    • Use lowercase or camelcase names for instances of a class

    I don't unterstand your aim, so here a short example:

    class Door {
      Door(){
        println("Created a door");
      }
      void open(){
        println("Open the door.");
      }
      void close(){
        println("Close the door.");
      }
    }
    
    class House {
      Door door;
      House(){
        door = new Door();
        println("Created a house");
      }
      Door getDoor(){
        return door;
      }
      void closeDoor(){
        getDoor().close();
      }
    }
    
    void setup(){
      House house = new House();
      house.getDoor().open();
      house.closeDoor();
    }
    
  • Duplicate with your other topic, see my answer there. Avoid posting the same question over several topics, please.

Sign In or Register to comment.