Milos Cuculovic
Milos Cuculovic

Reputation: 20223

Android: use a global object instead of creating new ones

I have a class A in my Android app where I have some methods. Those methods are public and used in other classes (B, C, D, E, F ...).

Is there a possibility to create only once the object from the class A and then use it in the other classes or i have to create new object in each classe.

Actually I have to do in each classe (B, C, D, E, F ...)

A a = new A();
a.xxxx;

It will be great if I can create only once the object a and then call it in my other classes.

thank you.

Upvotes: 1

Views: 1358

Answers (5)

user387184
user387184

Reputation: 11053

I see the following 3 possibilities:

1. If these are just "normal" helper methods you may also just do

class B extends A

and inherit the methods of A into B,C,D,E,....

2. However if you need internal memory of class A which is global to all other classes or their instances of B,C,D then may use the static pattern like

class A{

static int myGlobalIntVariable; //which is accessible from everywhere 
static void myHelperMethod1() {

}

or 3. Also you may use singleton as mentioned above which creates an instance that you use everywhere.

Just as a remark, you may use singleton or static pattern depending what you prefer when accessing the methods.

For static patter you have to call them like:

A.myHelperMethod();

and for singleton you have to do:

A.getSingleton().myHelperMethod1();  or A.singleton.myHelperMethod1()

if you have defined a variable called singleton within Class A

Which one to use really depends on your needs and taste :-)

Upvotes: 1

waqaslam
waqaslam

Reputation: 68177

Use static methods's analogy to do this.

For example:

public class Helper{
    public static void doSomething(){
        //do something here
    }
}

Now in your other classes, use the above method as below:

Helper.doSomething();

Or Singleton pattern would be an alternate too.

Upvotes: 2

ngesh
ngesh

Reputation: 13501

Instead of that why don't you make those methods static or consider single instance pattern if there are no states involved..

how to use static methods and singleton pattern

Upvotes: 1

Chandra Sekhar
Chandra Sekhar

Reputation: 19492

class A{
    static A a;
    static{
          a = new A();
    }
}

In every other class use

A.a to get the object and call respective methods as
A.a.xxxx()

Upvotes: 3

soren.qvist
soren.qvist

Reputation: 7416

Use a singleton pattern. It allows you to use the same instance across classes:

http://www.javabeginner.com/learn-java/java-singleton-design-pattern

Upvotes: 6

Related Questions