Static fields in a class

Is it possible to work with static fields in my own class in Processing? How to?
Here is an example of what I want to do:

Auto a;

void setup(){
  size(400,400);
  Auto.ctr=0;
  a=new Auto();
}

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

class Auto{

  static int ctr;
  Auto(){ctr++;}

  void draw(){text("Driving",width/2,height/2);}

}

However, I get an error: The field ctr cannot be declared static in an non-static inner type, unless initialized with a constant expression.

So, yes... If I do instead private static int ctr; then the error goes away but the functionality is lost. Is there a way to do this with a non-constant field at all?

Kf

Tagged:

Answers

  • edited January 2017

    but the functionality is lost.

    Why? you can't write a getter for it? never mind -- I see now what you were trying to do in setup. See GoToLoop below.

  • edited January 2017 Answer ✓
    // forum.Processing.org/two/discussion/20578/
    // static-fields-in-a-class#Item_2
    
    // GoToLoop (2017-Jan-31)
    
    Auto auto;
    
    void setup() {
      size(300, 300);
      noLoop();
    
      textAlign(CENTER, CENTER);
      textSize(Auto.SIZE);
      fill(#FFFF00);
    
      Auto.ctr = 10;
      auto = new Auto();
    
      println(auto); // 11
    }
    
    void draw() {
      background(0);
      auto.display();
    }
    
    static abstract class Counter {
      static int ctr;
    
      @ Override String toString() {
        return str(ctr);
      }
    }
    
    class Auto extends Counter {
      static final int SIZE = 40;
    
      Auto() {
        ++ctr;
      }
    
      void display() {
        text("Driving", width>>1, height>>1);
      }
    }
    
  • =D> Great, thxs. That will do for me.

    Kf

Sign In or Register to comment.