Using class-wide methods in non-static classes

After doing some research, I have yet to find a way to use static methods in a non-static class. Alternatively, I can’t create instances of an object of a static class. I did notice someone mention class-wide methods, but there was no information on the processing wiki.

Basically, all I want is a class that allows me to create objects, but also allows me to use static methods. For example if the class was named “Car”, I want to be able to say

Car c1 = new Car();

but also be able to write a method that is called as such:

Car.functionName();

I know this is possible in Java, but Processing 3 seems to be preventing me from doing it. Any help would be appreciated, thank you in advance!

B/c all classes inside a “.pde” file are nested inside a PApplet subclass, if we need to have static members inside them, we’re gonna need to declare those classes as static as well:

Ok, this is what you can do:

Close Processing. Create the following folder structure

C:\P3> tree ApolloMain /a /f

C:\P3\APOLLOMAIN
    ApolloMain.pde
    AutoCar.java

You have a folder called ApolloMain and inside you find a pde and a java file. Open Processing and open the pde. You will see that ApolloMain is one of your tabs and AutoCar.java is another tab. Now add the following code:

File extension pde

AutoCar car;
void setup() {
  size(600, 400);

  car=new AutoCar();
  println("Get some info: "+car.whatIsMyPlanet());
}

void draw() {
  background(0);
}

Java file

class AutoCar {

  static String PLANET="MARS";

  static String whatIsMyPlanet() {
    return PLANET;
  }

  AutoCar() {
  }
}

Run it. If you want to understand a bit more about what Processing in doing, go to file menu in the PDE and export the code. Then have a look at the generated Java files.

Kf

1 Like

Nice step-by-step @kfrajer. However, we can exceptionally have static fields inside inner classes as long as they’re final & either primitive or String; b/c in this case, they become compile-time constants: :grinning:

void setup() {
  final AutoCar car = new AutoCar();
  println("Planet:", car); // Planet: MARS
  exit();
}

class AutoCar {
  static final String PLANET = "MARS"; // Compile-time constant

  @Override String toString() {
    return PLANET;
  }
}