0

lets say I have classA and classB.

I know that I cannot just call a non static variable or method of classA from classB because the system doesn't know which instance of classA I want to use. but is there a way to specify which instance?

something like this: in class A I declare a static variable which whould hold the some sort of ID or context to the specific instance of the class

class classA{ static Instance instance onCreate(){ instance = thisInstance(); } Method1(){ } } 

then in class B I would refer to that instance like this:

 ClassA.instance.method1(); 

is something like this possible? if so, what is the exact syntax?

[Bonus]: if no, what is the simplest way invoke a method in a class from another class? I assume some sort of event handling would be required. (I come from the embedded c world)

2
  • 2
    Get a reference to the other object and call a method on it? You might want to take a step back and go over some Java basics. Commented Sep 21, 2013 at 2:12
  • you may just want to use the Singleton pattern Commented Sep 21, 2013 at 2:42

2 Answers 2

1

Declare a static member in ClassA

public class ClassA { public static ClassA object = new ClassA(); public void doStuff() { // do stuff } } 

Then in ClassB

public void someMethod() { ClassA.object.doStuff(); } 
Sign up to request clarification or add additional context in comments.

3 Comments

No this not what I'm trying to do, I want to call a method in classA thats defined in classA, not a built in method such as toString.
this wouldn't work either, I want reference to the classA that was created by launching the app, not any arbitrary copy of classA. ClassA in my case is my main activity.
ClassA.object is a static variable. Static variables are initialized only once, at the start of the execution. It is a single copy to be shared by all instances of the class. You could make a private constructor in ClassA to ensure, ClassA.object is the only instance of ClassA in your app.
0

In class B, you can define:

Class B { private static ClassA instanceA = null; // By making it null, you can later confirm that the instance was successfully passed by making sure instanceA != null. /** * This method allows you to pass the instance of ClassA into B so you can use its non-static methods. */ public static void setInstanceA(ClassA instance) { instanceA = instance; } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.