Using utility classes in the android programming

David Brown picture David Brown · Oct 14, 2010 · Viewed 21.9k times · Source

I have a little idea of the Utility Classes with a slight doubt on demand.

If I use a Utility class in my Application than to use that class in my main Activity do I have to create the object of that class or I can directly Import that class in my main activity?

I am Sorry if I am not making a clear sense.

In the nutshell, all I want to be clear about is that basically how can I use the utility class in my Main Activity?

Thanks, david

Answer

Cristian picture Cristian · Oct 14, 2010

It mainly depends on what your utility class does. But, most of the time, if you create an Utility class, you will want to create static methods and invoke them without creating an instance:

class MyUtilities{
    public static String foo(String bar){
        return bar.toUppercase;
    }
}

Then, on your activity:

MyUtilities.foo("baz");

Of course, there are cases where you will want to create instance of a Utility class. For instance, if you have created a global Adapter which will be used by all your ListViews.