I cant seem to find an answer on the internet anywhere.
So I have a processing project in Eclipse
I want to be able to access objects in my “main” class that extends PApplet in another class without having to pass them through the constructor. I am not the most experienced programmer so my terminology might be off but hopefully this example clarifies what I am trying to do.
so for
public class Main Extends PApplet{
//Example Class to access objects from main
Interaction interaction;
//Example Objects I want
boolean someObject;
void setup(){
someObject = true;
Interaction = new Interaction();
}
void draw(){
}
}
public class Interaction{
PApplet p;
public Interaction(PApplet parent){
p = parent;
}
public void mousePressed(){
if(someObject){
//do something
}
}
}
so I know I could pass that object into the constructor of Interaction like
PApplet p;
boolean o;
public Interaction (PApplet parent, boolean SomeObject){
p = parent;
o = someObject;
}
but this gets a little crazy in an example like this where I just want to hold all of my mouse and keyboard interaction in its own class because its getting huge, but I have run into the need to this time and time again and cant seem to figure it out.
What you are describing is called a
gettermethod.You can add a getter method to your
Main, but first read this -> http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.htmlHere is the example.
BTW,
booleanis not anObjectin Java,Booleanis.EDIT
After your comment I DO understand what you need.
You need to create an
interfaceand pass this interface toInteractionconstructor.This interface should provide all the method that your
Interactionneeds. If it needs an access toPApplet, then that’s what your interface should provide.With this in mind, here is a new hierarchy:
With these changes,
Interactioncould care less ifctxisMain,PAppletorUnicorn. Its constructor requests the expected behavior and your implementation ofMainprovides this behavior at runtime.In any case read the javaworld article and related articles.
Also, read articles about
Dependency Injection