Reputation: 3553
As I understand static
, it is that static methods can be called without an instance of the object needing to exist. So instead of making an object and calling the method on that object, you can just call the method on the class.
Now, I have a class Main
that has the following object: public ScribbleCanvas myCanvas;
. In the ScribbleCanvas
class I would like to access a method of the Main
-class.
Now, since there is already an instance of Main
(since this called the ScribbleCanvas
), how can I access a non-static method of this class? Or perhaps the better question - where is the error in my reasoning?
Upvotes: 0
Views: 114
Reputation: 2336
If I understand your question you want to:
Main
class, let's call it myMain
.ScribbleCanvas
class, called myCanvas
ScribbleCanvas
instance (myCanvas
) have access to methods within myMain
.In order to do this you can:
Main
within ScribbleCanvas
, say callingMain
Main
(say paramMain
) in the constructor for ScribbleCanvas
paramMain
in callingMain
Main
, pass in this
to the constructorcallingMain.method()
Does this help?
Upvotes: 1
Reputation: 12890
The below code explains how you should do it. The testInstanceMethod
is been taken as an
example for an instance method in Main class. This method should be accessible as well
public class ScribbleCanvas{
private Main mainObject = null;
public ScribbleCanvas(){
this.mainObject = new Main();
//Call instance method in mainObject (member instance)
this.mainObject.testInstanceMethod();
}
public void setMainObject(Main arg){
this.mainObject = arg;
}
public Main getMainObject(){
return this.mainObject;
}
}
For invoking static methods, you can directly put the Classname and invoke using DOT operator like Main.testStaticMethod()
provided the method is accessible as well
Disclaimer : NOT tested / compiled
Upvotes: 1
Reputation: 8960
You could have a constructor or a setter for the ScribbleCanvas
that takes a parameter as the current instance of Main
.
ScribbleCanvas sc = new ScribbleCanvas(this);
or
sc.setMainClass(this);
And with those, you just reference a field to the parameter.
Upvotes: 1
Reputation: 19304
You can set Main
instance as a member of myCanvas
and use it.
Upvotes: 1