Private Keyword Example?
in
Programming Questions
•
1 month ago
Hey all,
I'm creating Processing tutorials for my little site, and I'm working on an OOP tutorial. I'd like to show an example of the private keyword (even though it's not really used in Processing, I was hoping to teach the concepts before jumping in to Java).
My idea was to show an example sketch where a ball chased the mouse when it was clicked. That works great. Then I wanted to expand that example and ask "what if you were working on a team, and somebody used the wrong variable from your Ball class?". Something like this:
I'm creating Processing tutorials for my little site, and I'm working on an OOP tutorial. I'd like to show an example of the private keyword (even though it's not really used in Processing, I was hoping to teach the concepts before jumping in to Java).
My idea was to show an example sketch where a ball chased the mouse when it was clicked. That works great. Then I wanted to expand that example and ask "what if you were working on a team, and somebody used the wrong variable from your Ball class?". Something like this:
- Ball ball = new Ball();
void setup() {
size(500, 500);
ellipseMode(CENTER);
}
void draw() {
background(0);
ball.draw();
}
void mouseClicked() {
//was hoping for a compiler error here
ball.x = mouseX;
ball.y = mouseY;
}
class Ball {
private int x = 250;
private int y = 250;
int targetX = 250;
int targetY = 250;
void draw() {
if (x < targetX) {
x++;
}
else {
x--;
}
if (y < targetY) {
y++;
}
else {
y--;
}
ellipse(x, y, 25, 25);
}
}
I was hoping that the mouseClicked() method would result in a compile-time error, showing how you could use the private keyword to protect the variables you don't want other code messing with. But alas, this code runs fine.
I realize that this is happening because classes in Processing are inner classes, and private variables in inner classes are available to outer classes in Java... but is there a better way to show the use of the private keyword in Processing? Or is it just *never* used at all?
Appreciate any input or suggestions!
Kevin
1