MOBI BOOT CAMP CORP. logoLearning Buddy
  • SIGN IN
  • Introduction
  • Unit 0: The First Program
  • Unit 1: Using Objects and Methods
    • Part 1: Fundamentals
    • Part 2: Operations and Documentation
    • Part 3: Objects and Classes
      • Calling Class Methods
      • Math Class
      • Objects: Instances of Classes
      • Object Creation and Storage (Instantiation)
      • Calling Instance Methods
      • Types of Variables
      • Pass by value/reference
      • String Manipulation
      • Unit 1 Part 3 Slides
  • Unit 2: Selection and Iteration
  • Unit 3: Class Creation
  • Unit 4: Data Collections

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();
    }
}
Static vs Instance Method Calls
Privacy Policy | Terms & Conditions