Explain Class Methods in Java with example

Class Methods in Java

Class methods in Java (also known as static methods) are methods that belong to the class rather than to any specific instance of the class. They can be called without creating an instance of the class.

Key Points about Class Methods in Java

  • Declared with static Keyword: Class methods are defined with the static keyword.
  • Cannot Access Instance Variables Directly: Since they belong to the class itself and not to any object instance, they cannot directly access instance variables or instance methods.
  • Can Access Static Variables and Methods: They can access other static methods and static variables directly.

Example of Class Methods in Java

Let’s consider a simple example:

public class MathUtil {
    // Static variable
    static final double PI = 3.14159;

    // Static method to calculate the area of a circle
    public static double calculateCircleArea(double radius) {
        return PI * radius * radius;
    }

    // Static method to calculate the circumference of a circle
    public static double calculateCircleCircumference(double radius) {
        return 2 * PI * radius;
    }

    public static void main(String[] args) {
        double radius = 5.0;

        // Calling static methods without creating an instance of MathUtil
        double area = MathUtil.calculateCircleArea(radius);
        double circumference = MathUtil.calculateCircleCircumference(radius);

        System.out.println("Area of the circle: " + area);
        System.out.println("Circumference of the circle: " + circumference);
    }
}

Explanation of the Example:

  • Static Variable PI: This is a static variable that holds the value of π (pi). It is declared as static final meaning it’s a constant and can be accessed without creating an instance of the class.
  • Static Methods
    • calculateCircleArea(double radius): This method takes the radius of a circle and returns the area. It uses the static variable PI.
    • calculateCircleCircumference(double radius): This method takes the radius of a circle and returns the circumference.
  • Main Method
    • The main method is also static and serves as the entry point for the program.
    • It calls the static methods calculateCircleArea and calculateCircleCircumference directly using the class name MathUtil.

In this example, calculateCircleArea and calculateCircleCircumference are class methods and can be called directly using the class name without needing an instance of MathUtil.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *