Week 09
Week 09
2
Content
and is available for the entire duration of a program's run. Static variables are shared across
Static variables are used with the class name and the dot operator, since they are associated
with a class, not objects of a class. Static methods cannot access or change the values of
instance variables, but they can access or change the values of static variables.
3
Static Method
A static method in Java is a method that is part of a class rather than an instance of that class.
Static methods have access to class variables (static variables) without using the class’s object (instance).
Only static data may be accessed by a static method. It is unable to access data that is not static (instance
variables).
In both static and non-static methods, static methods can be accessed directly.
4
Static Method
5
How to use a static method
6
How to use a static method
7
Static variables and static methods are in the same class
A static method can access any static variable or static method without any object creation.
class StaticMethodExample
{ public static void main(String arg[])
int a = 0; {
static int b = 0; displayData();
void showData() StaticMethodExample obj = new
{ StaticMethodExample();
System.out.println("Value of a : "+ a); obj.showData();
System.out.println("Value of b : "+ b); }
} }
static void displayData()
{
StaticMethodExample obj = new
StaticMethodExample();
System.out.println("Value of a : "+ obj.a);
System.out.println("Value of b : "+ b);
}
8
Static variables and static methods are in the same class
A static method can access any static variable or static method without any object creation.
9
Static variables and static methods in Different Class
A static method can access any static variable or static method without any object creation.
10