STATIC METHODS AND VARIABLES Static Methods: Methods in Java can be either Static or non-static. The non-static methods are called Instance Methods. Instance methods are associated with an object and use instance variables of that object. If you have a class and it has methods that are not preceded by the keyword ‘static’, the are called instance methods. Example: Class Test { int
a;
Instance variable/ Non-static variable Static variable
static int b; void
normalMethod() { }
Instance Method/Nonstatic method
static void myStaticMethod() { a = 4; } }
Static Method
public class mainClass { public static void main(String[] args) { Test tobj = new Test();
Creating an Instance of class Test. An object ‘tobj’ is created.
System.out.println(Test.b); tobj.a = 5; System.out.println(tobj.a);
Test.myStaticMethod();
Access instance variable using the object ‘tobj’
Call static methods using class name
tobj.normalMethod(); } }
Call Instance method using Object ‘tobj’.
•
A static variable is called a “Class variable”.
•
A static variable/class variable can be accessed directly w/o the need to create an instance. Example: In the above program, the static variable ‘b’ can be accessed by the statement System.out.println(Test.b); Here ‘Test’ is the class within which the variable ‘b’ resides.
•
Static methods use no instance variables of any object of the class they are defined in. Example: In the above program for the static method ‘mystaticMethod()’, the variable ‘a’ cannot be used in the body of the method, as ‘a’ is an instance variable. We see an error saying ‘non-static variable cannot be referenced from static context’. Static variables can be used with static methods. Instance variables can be accessed only by instance methods. Static methods are called using class name if doing from other classes. Instance methods are called using instance of that class.
• • •