Unit 1.10: Class Methods
Static Methods
Class methods, also known as static methods, are associated with the class itself rather than a specific instance (object) of the class.
Class-Level Behavior
- Static methods belong to the class, not to any specific object. A static method can only directly call other static methods within a class.
They are defined using the static keyword. Because static methods belong to the class as a whole, they cannot access instance variables (data tied to a specific object). The main method is the most common example of a static method.
Task: Defining and calling a static method within the same class.
public class Greeter {
// This is a static method
public static void sayHello() {
System.out.println("Hello, World!");
}
public static void main(String[] args) {
// We can call the static method directly because we are inside the same class
sayHello();
}
}
Calling Class Methods
Class methods are typically called using the class name, followed by the dot operator (.), the method name, and any required arguments.
The Dot Operator
- The
.symbol is used to access members of a class or object. For static methods, it tells Java which class contains the code you want to run.
However, if you are calling a static method from within the class where it is defined, providing the class name is optional.
Task: Calling a static method from a different class.
// Assume the Greeter class is defined as above
public class Main {
public static void main(String[] args) {
// Calling the sayHello class method from the Greeter class
// using the format: ClassName.methodName()
Greeter.sayHello();
}
}