Questions
What does static mean? When would I use static or “non-static”?
Answer
- A method declared “static” can be called directly without having an object through which to run it. Technically, it is part of the class.
- “Non static” methods can only be called through an object. Technically, they are only a part of the instance of the class.
- “Static” variables are variables that have the same value across all objects of that class. If the value is changed in one object, the value is changed for all objects of that class.
Example
Public class MyMethods{
public static int number; //static variable. I declared it public so that it can be changed easier.
// The static method
public static void myStaticMethod()
{
//code for myStaticMethod
}
// The non-static method.
public void myNonStaticMethod()
{
{
} //class MyMethods
//Main Program
public class MyMethodsMain
{
#include MyMethods
public static void main (String[] args)
{
myStaticMethod();
// myStaticMethod can be called without creating an object.
MyMethods newObject = new MyMethods();
newObject.myNonStaticMethod();
// myNonStaticMethod can only be called from within the object itself. It cannot be called directly.
// You have to create an object to use it.
MyMethods newObject2 = new MyMethods();
newObject.number = 5;
System.out.println(newObject2.number);
// This will print the value 5 even though the value for newObject2 was never changed because number is a static.
// number is the same for all MyMethod objects.
}
} //class MyMethodsMain
Other Resources
T2 Lesson 5: Static vs Non-Static methods