Skip to content Skip to sidebar Skip to footer

Having A Difficult Time Making A Static Method Which Utilizes Non-static Methods

I'm about 6 weeks into learning Java and still struggling with implementing static methods (thought I really understood it, but this proved me wrong!). I'm trying to make the value

Solution 1:

I think you might be misunderstanding how static works.

A static method (or variable) is one that has a single copy for all instances of the class and does not require and instance of the class to invoke it. For example,

classMyClass {
      publicstaticvoidsayHello() {
          System.out.println("hello");
      }
 }

That can be invoked as

MyClass.sayHello();

Notice there is no new instance of MyClass created.

An instance method is one that requires a particular instance of a class and usually relies on some internal state of the class.

classMyClass {

    // assume this is initialized somewhere in the constructorprivate final String myName;

    publicvoidsayMyName() {
        System.out.println(myName);
    }
}

Now you would need a specific instance of the class

MyClass m = newMyClass("Bill");
m.sayMyName();

A static method cannot reference an instance method (or instance variable) because a static method is not tied to a particular instance of a class.

Non-static methods can access both non-static and static methods.

In general, if a method relies on state of the instance, it should be a non-static method. If it does not rely on internal state of the instance, then it can be a static method.

In your case, getSharedPref does not access any state from the instance of Settings, so it can be made into a static method and can then be accessed by other static methods in the class.

Solution 2:

If you want to write a static method that utilizes non-static methods, you just pass an instance to it like this:

publicstaticvoidinvokeMethod(SomeObject foo) {
    foo.bar();
}

So what you're doing is a great pattern. I use it all the time for "helpers" that can be reused across many classes (aka composition) Just make your "SomeObject" the Context.

Here's the pattern I use in Android to get a nice central point to define default preferences:

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

import java.util.HashMap;
/**
 * Provides support functions for getting preferences as well as a
 * central place for storing default preferences.
 */public final classPreferencesHelper {
    publicstaticclassPreferences {
        publicstatic final StringSOME_SETTING = "SOME_SETTING";
    }

   /** This allows us to define our default preferences all in one place */privatestaticHashMap<String, Object> sDefaultPreferences =
        newHashMap<String, Object>(){{
        put(Preferences.SOME_SETTING, "value");
    }};

    publicstaticSharedPreferencesgetDefaultPreferences(Context context) {
        returnPreferenceManager.getDefaultSharedPreferences(context);
    }

    publicstaticStringgetString(SharedPreferences prefs, String key) {
        return prefs.getString(key, (String) sDefaultPreferences.get(key));
    }

    /* Convenience method (use when getting only one preference) */publicstaticStringgetString(Context context, String scanner) {
        SharedPreferences prefs = getDefaultPreferences(context);
        returngetString(prefs, scanner);
    }

...

This pattern allows the definition of default values to be in one place.

Solution 3:

You can't access a non-static method from inside of a static method. what you are doing here is the same thing. You are accessing a non-static method, namely, getSharedPref() from inside of a static method getDriverNum

Solution 4:

Simply, you need to know two things:

  1. you can call static methods in non-static methods

  2. you cannot call non-static methods in static methods in the same class (except you new a instance of another class, and call non-static methods by that objects)

that's why you get error, you break the second rule when you callgetSharedPref() in getDriverNum().

To solve this, try to make getSharedPref() static, and in return make getSharedPreferences() static.

Solution 5:

In your Helper class, just pass it the static variable of the Activity class. e.g.

HelperClass:

publicstaticintgetDefaultYear()
{
    return HomeActivity.prefs.getInt("myYear", 10);
}

HomeActivity:

publicclassHomeActivityextendsAppCompatActivity {

publicstatic SharedPreferences prefs;

@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   prefs = this.getSharedPreferences(getString(R.string.applicationIdString), Context.MODE_PRIVATE);
   ...
   }

Post a Comment for "Having A Difficult Time Making A Static Method Which Utilizes Non-static Methods"