We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Static Fields & Methods in Non-Static Class
Page Index Toggle Pages: 1
Static Fields & Methods in Non-Static Class (Read 583 times)
Static Fields & Methods in Non-Static Class
Feb 7th, 2009, 2:54am
 
Example: the classic singleton pattern.

Code:
public class Singleton {
private static Singleton instance = null;
protected Singleton () { }
public static Singleton getInstance() {
if(instance == null) { instance = new Singleton(); }
return instance;
}
}


Processing responds to this with the message, "The field instance cannot be declared static; static fields can only be declared in static or top level types."

Is there any reason why the ENTIRE class is required to be static? Is there any way around this restriction?
Re: Static Fields & Methods in Non-Static Clas
Reply #1 - Feb 7th, 2009, 11:13am
 
All code in a .pde file (and other .pde files in the same sketch) is gathered into a single class named along the name of the sketch.
It is convenient in general, and works well in most cases, as classes can be nested, global variables are actually fields of the invisible enclosing class, etc.

But Java introduce limitations like restrictions on static stuff and no interfaces there.

To avoid this problem, Processing allows to put .java files in the sketch as well: they will be compiled to .class files independently of the main class. That's what you need.
The only catch is that you don't have the Processing functions available there, unless you pass an instance of the main class to them.
Page Index Toggle Pages: 1