Reputation: 10948
I have a question : So i have this line of code(i got it from tuts in thenewboston) :
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
My question is : what did we do in this line? i think we create an object from SharedPreferences, but what about the PreferenceManager Class?is it the super Class of SharedPreference?is it has some relation with OOP?
Thanks all ~
PS : English is not my native languange, so sorry if i made some mistake's :D
Upvotes: 1
Views: 104
Reputation: 125
You are actually creating an instance of an object. SharedPreferences is the object type you are creating, and the variable getPrefs refers to the instance. PreferenceManager is an already-intanciated object, containing method named 'getDefaultSharedPreferences', returning an SharedPreferences object instance.
To make an example, try to understand this:
Human Chris = Room.pushOutSomebody();
:)
Upvotes: 1
Reputation: 174624
This snippet of code creates a new variable of type SharedPreferences
called getPrefs
, and sets its value to the return value of the method getDefaultSharedPreferences
of the PreferenceManager
class.
Upvotes: 1
Reputation: 11075
The PreferenceManager has a static method named getDefaultSharedPreferences. What this means is that you can call the method without first constructing an instance of 'PreferenceManager'. Static methods do not operate on instance variables within a class.
Static methods can create instances of objects, and return them. In this case, the static method created a new SharedPreferences object that you're storing in a local variable.
Think of it like this: A static method exists once for all the instances of an object. Every time you call that static method, it's doing the same thing regardless of what each object might know. Based on the context passed into it, it will create a SharedPreferences object that you can use.
I hope this helps!
Upvotes: 2
Reputation: 2976
PreferenceManager is a class. ie: a type. If you have 'int i;' int is the type, i is the instance variable.
getDefaultSharedPreferences() is a static method - meaning that it can run without an instance object. That's why it is a type before the '.' and not a variable/instance.
Upvotes: 1