0

I'm a beginner learning java and andorid so please bear with me even if the question sounds idiotic.

So from what i know from java, in order to call a non static method, class must be initiated.

But i came across a code like below

might not be correct since i'm writing off of my memory

SharedPreferences shared = getsharedpreference("i",String)

here getsharedpeference which is a method inside ContextWarpper is called without creating the class. The method seems to be non static, so i am wondering how this is possible?

Vojin Purić
  • 2,140
  • 7
  • 9
  • 22
  • How can it be "inside a class" if there's no instance of the class? What makes you think there's no instance of the class this code is from? – Dave Newton Nov 23 '21 at 23:32
  • 1
    Can you point towards the code where saw this? Your scenario cannot happen because all instance methods need an instance of the class. The android framework code initializes (creates instances) a bunch of things for you - some examples are your application, activities etc. – Naveed Nov 24 '21 at 00:00
  • Code like that could be called within a method in an `Activity`, and would be the same as calling `this.getSharedPreferences()` (since in that case `this` is a context). Some examples [here](https://stackoverflow.com/a/9255684/9473786). – Tyler V Nov 24 '21 at 04:55

1 Answers1

0

This is dependent on which Activity is being used but they all boil down to the same thing.

android.app.Activity extends android.view.ContextThemeWrapper

android.view.ContextThemeWrapper extends android.content.ContextWrapper

android.content.ContextWrapper extends android.content.Context

In android.content.Context the function

public abstract SharedPreferences getSharedPreferences (String name, 
                int mode)

exists and it is public meaning through inheritance all classes that extend it have access to the function.

Through a series of inheritance android.app.Activity can use a function that does not exclusively belong to it.

avalerio
  • 2,072
  • 1
  • 12
  • 11