3

if look at SharedPreferences it clearly shows it's an interface in Android SDK.

public interface SharedPreferences

Can anyone help me understand it better that which class exactly provides definition to functions of SharedPreferences?

turbandroid
  • 2,296
  • 22
  • 30
  • Question is about implementation of [SharedPreferences](http://developer.android.com/reference/android/content/SharedPreferences.html), I know it's interface but not able to find which class give it definition. – turbandroid Dec 15 '15 at 11:11

2 Answers2

4

It is an interface, there's no mistake in android's documentation. As you can see in SharedPreferences's source code too:

public interface SharedPreferences {

Digging in android's source code, we can see that Activity extends from ContextWrapper

public class Activity extends ContextThemeWrapper
    implements LayoutInflater.Factory2,
    Window.Callback, KeyEvent.Callback,
    OnCreateContextMenuListener, ComponentCallbacks2,
    Window.OnWindowDismissedCallback {

Looking at ContextWrapper.java, it calls getSharedPreferences function from Context class

Context mBase;

@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
    return mBase.getSharedPreferences(name, mode);
}

Which is declared as an abstract function in Context.java,

/**
 * Interface to global information about an application environment.  This is
 * an abstract class whose implementation is provided by
 * the Android system.  It
 * allows access to application-specific resources and classes, as well as
 * up-calls for application-level operations such as launching activities,
 * broadcasting and receiving intents, etc.
 */
public abstract class Context {

    public abstract SharedPreferences getSharedPreferences(String name, int mode);

}

In conclusion SharedPreferences is implemented in a class(as every interface) on every Context implementation. If we take a look at the comments in Context's source code we can see that:

This is an abstract class whose implementation is provided by the Android system

And in case that you want more information about Context, here is way more info: What is Context in Android?

Community
  • 1
  • 1
Santiago Hernández
  • 5,438
  • 2
  • 26
  • 34
1

getSharedpreference() is the function of ContextWrapper class. And ContextWrapper class is extended by Every Activity class.

When we use getSharedpreference() method then it is called by context class. It is in the context class object. But it returns the Sharedpreferences object. Shared preferences is not a class it is a interface. getSharedpreference() is use only reference of this interface.

Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135