jdepypere
jdepypere

Reputation: 3553

Confusion about static methods in Java

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

Answers (4)

Auspice
Auspice

Reputation: 2336

If I understand your question you want to:

  • Have an instance of the Main class, let's call it myMain.
  • The instance will have an instance of the ScribbleCanvas class, called myCanvas
  • From the ScribbleCanvas instance (myCanvas) have access to methods within myMain.

In order to do this you can:

  • Declare a member of type Main within ScribbleCanvas, say callingMain
  • Include a parameter of type Main (say paramMain) in the constructor for ScribbleCanvas
  • In the constructor, store paramMain in callingMain
  • From Main, pass in this to the constructor
  • Within your code, you can refer to callingMain.method()

Does this help?

Upvotes: 1

Keerthivasan
Keerthivasan

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

Georgian
Georgian

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

BobTheBuilder
BobTheBuilder

Reputation: 19304

You can set Main instance as a member of myCanvas and use it.

Upvotes: 1

Related Questions