Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Class Methods

In Java, a class method, also known as a static method, is a method that belongs to the class rather than an instance of the class. Class methods can be called without creating an object of the class and are often used for utility functions that don't depend on the state of an object.

In this tutorial, we'll explore how to create and use class methods in Java.

  • Creating class methods:

To create a class method, use the static keyword before the method's return type. Here's an example:

public class MathUtils {

    public static int add(int a, int b) {
        return a + b;
    }

    public static int subtract(int a, int b) {
        return a - b;
    }
}

In this example, the MathUtils class has two class methods: add() and subtract(). These methods don't depend on the state of any object and can be called directly using the class name.

  • Calling class methods:

To call a class method, you don't need to create an object of the class. Instead, use the class name followed by the dot (.) operator and the method name. Here's an example:

public class Main {

    public static void main(String[] args) {
        int result1 = MathUtils.add(5, 3);
        int result2 = MathUtils.subtract(5, 3);

        System.out.println("Addition: " + result1);        // Output: Addition: 8
        System.out.println("Subtraction: " + result2);     // Output: Subtraction: 2
    }
}

In this example, we call the add() and subtract() methods of the MathUtils class without creating an object of that class.

  • Accessing class fields in class methods:

Class methods can access only static fields (class variables) of the class, not instance fields (instance variables). Here's an example:

public class MathUtils {

    public static final double PI = 3.14159265359;

    public static double calculateCircleArea(double radius) {
        return PI * radius * radius;
    }
}

In this example, the MathUtils class has a static field PI and a class method calculateCircleArea(). The method uses the value of PI to calculate the area of a circle with the given radius.

  • Restrictions on class methods:
  • Class methods cannot access instance fields or call instance methods directly. They can only access static fields or call other static methods.
  • Class methods cannot use the this keyword, as it refers to an instance of the class, and class methods are not associated with any instance.

Class methods are an essential feature in Java that allows you to create utility functions or methods that don't depend on the state of an object. By using class methods, you can call methods directly using the class name without creating an object of the class.

  1. Defining and Calling Methods in Java Classes: Methods in Java are defined within classes and can perform specific tasks. Here's a basic example:

    public class MyClass {
        // Method definition
        public void sayHello() {
            System.out.println("Hello, World!");
        }
    
        public static void main(String[] args) {
            // Method invocation
            MyClass obj = new MyClass();
            obj.sayHello();
        }
    }
    
  2. Static vs. Instance Methods in Java Classes:

    • Static Methods: Belong to the class itself, accessed using the class name.
    • Instance Methods: Belong to instances of the class, accessed using object instances.
    public class MathOperations {
        // Static method
        public static int add(int a, int b) {
            return a + b;
        }
    
        // Instance method
        public int multiply(int a, int b) {
            return a * b;
        }
    }
    
  3. Java Method Overloading and Overriding in Classes:

    • Method Overloading: Defining multiple methods with the same name but different parameters.
    • Method Overriding: Providing a specific implementation of a method in a subclass.
    public class Shape {
        public void draw() {
            // Default implementation
        }
    }
    
    public class Circle extends Shape {
        // Method overriding
        @Override
        public void draw() {
            // Specific implementation for circles
        }
    
        // Method overloading
        public void draw(int radius) {
            // Overloaded method
        }
    }
    
  4. Access Modifiers for Java Class Methods: Control the visibility of methods using access modifiers (e.g., public, private, protected, or package-private).

    public class MyClass {
        // Public method
        public void publicMethod() {
            // Code here
        }
    
        // Private method
        private void privateMethod() {
            // Code here
        }
    }
    
  5. Return Types in Java Class Methods: Methods can have different return types, including primitives, objects, or void (no return value).

    public class Calculator {
        // Method with int return type
        public int add(int a, int b) {
            return a + b;
        }
    
        // Method with void return type
        public void displayResult(int result) {
            System.out.println("Result: " + result);
        }
    }
    
  6. Java Class Method Examples for Beginners: Here's a simple example with multiple methods performing different tasks.

    public class Example {
        public void greet() {
            System.out.println("Hello!");
        }
    
        public int addNumbers(int a, int b) {
            return a + b;
        }
    
        public static void main(String[] args) {
            Example obj = new Example();
            obj.greet();
            int sum = obj.addNumbers(3, 5);
            System.out.println("Sum: " + sum);
        }
    }
    
  7. Method Parameters and Arguments in Java Classes: Parameters are variables declared in a method signature, while arguments are the values passed when calling the method.

    public class Calculator {
        public int add(int num1, int num2) {
            return num1 + num2;
        }
    
        public static void main(String[] args) {
            Calculator calc = new Calculator();
            int result = calc.add(10, 20); // 10 and 20 are arguments
        }
    }