Get class variables from another class

How do I get a variable from the class that created the class ?

One a;

void setup() {
  a=new One();
}
void draw() {}

public class One {
  Two b;
  int num;

  One() {
    num=9;
    println(num);
    b=new Two();
  }
}
class Two {
  Two() {
    println(a.num);  //  error  How do I get the num variable ?
  }
}
1 Like

Is this a trick question?

I think in the above code the issue is that you try use a before a‘s constructor is finished

The println line itself is okay

2 Likes

Not a trick question. Simply asking how to get a variable from another class.

1 Like

hm, possibly you wanted this?

//One a;
Two b;

void setup() {
//  a=new One();
  b=new Two();
}

void draw() {}

public class One {
//  Two b;
  int num;
  One() {
    num=9;
    println("from One: "+num);
//    b=new Two();
  }
}

class Two extends One{
  Two() {
    println("from Two b "+num);
  }
}
// not even need super(..)

2 Likes

I think that’s the right way

The reason why it didn’t work is that you use it in the constructors

I didn’t mean to be rude

3 Likes

here

this shows that you can access a value from another class / object via println(a.num);

As I explained, the issue was outside this line.

Note that a is a global object and therefore known inside class Two




One a;

void setup() {
  a = new One();
}

void draw() {
  a.display();
}

// ====================================================

public class One {
  Two b;
  int num;

  One() {
    //constr
    num=9;
    println(num);
    b=new Two();
  }

  void display() {
    b.display();
  }
}//class

// ====================================================

class Two {
  Two() {
    //constr
  }

  void display() {
    println(a.num); // no error
  }
}//class
//
3 Likes

No, you weren’t rude. Thanks for the help

1 Like