Java Access Modifiers

https://processing.org/reference/private.html:

This keyword is used to disallow other classes access to the fields and methods within a class. The private keyword is used before a field or method that you want to be available only within the class. …

I tried, but still got access to a private method:

// “main file” ProcessingPrivateTest.pde

void setup () {
cMyClass myObject = new cMyClass ();
println (myObject.getX ());
println (myObject.getY ()); // WHY IS THIS ALLOWED?
} // < setup

void draw () {
} // < draw

// file cMyClass.pde in same directory (-> tab above)

class cMyClass {
int x, y;

cMyClass () {
x = 8; y = 12;
} // < cMyClass::cMyClass

int getX () {
return x;
} // < cMyClass::getX

private int getY () {
return y;
} // < cMyClass::getY
} // < class cMyClass

There are different types of class - this one is an inner class so the enclosing class (your sketch) has access to all its attributes no matter what the specifier.
Change the class to a top-levl class with
public static class cMyClass {
and see what happens

Thanks for the answer - anyhow after adding “public static” I can still access private method getY from “main” file.

1 Like
  • Everything inside “.pde” files are concatenated as 1 “.java” file before compilation.
  • Also they’re wrapped up as 1 PApplet subclass.
  • B/c everything is a member of that 1 class, nothing is actually private among them.
  • So it’s pretty much moot declaring those members w/ private or protected.
  • However, if any “.pde” member happens to be accessed outside its PApplet subclass, its access level kicks in.
  • If you really wish to have access levels on your classes, you’re gonna need to place them on a separate “.java” file, then import them inside a “.pde” file.
1 Like