Why can't I create my class after I declare a variable with it?

<

Ball ball;

class Ball {
  
}

I swear this code worked in processing 4.1.1 or maybe 4.0b7 cause that was how the tutorial worked(well the class is in a different file but processing reads it like tht so it does not matter) can someone tell me what changed, please

I this the entire Sketch?

I think that you need setup and draw to run it.

Also, I think you can’t save the Sketch with a name that is also a class name. So save it as Ball1 or BallExample

3 Likes

Hi

1 Like

main pde and the pde with the class must be in the same folder

so, processing does something?

Do you receive an error message or what happens?

1 Like

Draw or setup is not required, since you can run an empty sketch

Those were the exact tutorials i watched

Yes, they were in the same folder and processing reads files in the order: First the main file and then the other files in alphabetical order

I think that you need setup and draw to run it.

Also, I think you can’t save the Sketch with a name that is also a class name. So save it as Ball1 or BallExample

I can’t imagine that this has worked in processing not in p3 and not in p4.

You are using something called static mode (without setup/draw) and you can only have simple instructions for it.

Other mode is active mode (with setup and draw).

The reason, why it isn’t work is how processing assembles the result.
In static mode it wraps everything inside

public class sketch_static extends PApplet {
 public void setup() {
   // Static mode code goes here
 }
// Some other code like settings
}

The opposite on active mode

public class sketch_active extends PApplet {
   // all active mode code (*.pde) goes here
}

means your code would work in active mode but not in static mode.

And also consider this from @Chrisir …

Cheers
— mnse

class Ball {
}

Ball ball = new Ball();
println(ball);

exit();

Yes, that would be the solution but im trying to avoid defining it before everything else

You need setup and draw anyway so just enter these and tty this…?

When we click the “Run” :arrow_forward: button, the PDE concatenates all the “.pde” files as 1 “.java” file, and they’re also wrapped up inside 1 PApplet subclass.

My “fixed” posted example would become something like this “.java” file:

// ...

public class sketch_static extends PApplet {
  public void setup() {
    class Ball {
    }

    Ball ball = new Ball();
    println(ball);

    exit();
    noLoop();
  }

  static public void main(String[] passedArgs) {
    // ...
  }
}

So the whole “static” code, besides being wrapped up in 1 PApplet subclass, it’s also been moved inside callback method setup().

Although Java doesn’t allow us defining a method inside another method, surprisingly we can define classes inside methods!

In such case the order is important, b/c we have to define an internal class before we could instantiate it via new.

1 Like