0

I know basics of java programming and currently trying to make android apps. I know that making anything static is a good practice as it helps in memory management. Because, if a variable can be shared by all instances of a class then its better to have that variable as static rather than let all instances have their own copy of that variable(hence increasing memory required to load the class).

I read this answer to a very similar question, but wasn't quite able to understand it.

Referring to above answer, it says that- static fields are attached to class instance, well doesn't each instance have all methods, variables and static/non static nested classes attached to itself?

My Actual Question-

Earlier, I was going through this guide for understanding viewpagers. I noticed that the myPagerAdapter class was made static. What was the use of it?

Community
  • 1
  • 1
Rohan Bhatia
  • 1,870
  • 2
  • 15
  • 31
  • If my post is not useful, please give me suggestions. I am new to this community and there's still so many things that I need to learn. – Rohan Bhatia Dec 29 '16 at 17:04

1 Answers1

0

A static variable belongs to the class and is shared by all the instances of the class. There is only one copy per class. In contrast, an instance variable is not shared with other instances. Each instance has its own copy of the variable.

You can argue that a static variable saves on memory. But when deciding whether or not the static keyword should be used with a variable, I think what is more important is to determine whether the piece of information represented by that variable should be shared by all instances of the same class (i.e. there should be just one copy per class), or each instance needs to have its own copy.

leeyuiwah
  • 6,562
  • 8
  • 41
  • 71