IT Elective 1
Object-Oriented Programming
Static Methods and Fields
static
This keyword is another modifier that tells the
compiler that there is exactly one (1) copy of
this variable in existence, regardless of how
many times the class has been instantiated.
static
Just like the access modifiers, it can be declare
in class members:
Field Variables
Methods
Can be mixed with other access modifiers
Method Declaration
public static void main(String args[]){
}
Example of static method
Return type
Static modifier
static void myMethod(){
//package-default static method
} Method name
Method body
Example of static method with access
modifier Return type
Static modifier
private static void myMethod(){
//private static method
} Method name
Method body
Access modifier
//in between access modifier and return type ✔
//before the access modifier
✔
//before (or even after) the method name
✖
Example of static field variables
✔
✔
//package-default static variable
✔
//between access modifier and return type
//before the access modifier
//before (or even after) the variable name
✖
Rules
for calling static members
Static methods can only directly call static members.
//a static variable
//a non-static (instance) variable
//a non-static (instance) method
Rules
for calling static members
//create an instance of the
class to call non-static
members to static methods
Rules
for calling static members
//You can still call static members through the
instance, though it is same as using the code
above.
Rules
for calling static members
//You can still call static members through instance methods.
Rules
for calling static members
When accessing static members to other class, the class name
where the members are from should be used.
//a static variable
//a non-static (instance) variable
//a non-static (instance) method
Rules
for calling static members
Rules
for calling static members
//treated as the same.
Rules
for calling static members
//You can still call static members through instance methods
of other class using the class name.
Demonstration
//MyClass.java
//YourClass.java
//constructor
Demonstration
Output
Demonstration
Output
Demonstration
Output
Demonstration
Output