Showing posts with label static vs non static methods. Show all posts
Showing posts with label static vs non static methods. Show all posts

Friday, July 7, 2023

Difference between static vs non static method in Java - Example

In Java, methods can be classified as static or non-static. The main difference between these two types of methods lies in their behavior and how they are accessed. Here's an explanation with an example: 

 Static Methods: 

Static methods are associated with the class itself, rather than with any specific instance of the class. 

They can be accessed directly using the class name, without creating an object of that class. 

Static methods cannot access instance variables or invoke non-static methods, as they are not tied to any specific object. 

They are typically used for utility functions, calculations, or operations that don't require access to instance-specific data. 

Example:


public class MathUtils {
    public static int square(int number) {
        return number * number;
    }
}

In this example, the square() method is defined as static. It can be accessed using the class name MathUtils.square(5), without creating an object of the MathUtils class. 

Non-Static Methods: 

Non-static methods are associated with individual instances (objects) of a class. 

They can access both static and non-static members of the class, including instance variables and other non-static methods. 

Non-static methods are invoked on an object of the class by referencing that object. 

They can be overridden in subclasses to provide different behavior. 

Example:


public class Circle {
    private double radius;
    
    public Circle(double radius) {
        this.radius = radius;
    }
    
    public double calculateArea() {
        return Math.PI * radius * radius;
    }
}

In this example, the calculateArea() method is non-static. It calculates the area of a circle based on its radius, which is an instance variable. 

To invoke this method, you need to create an object of the Circle class, like Circle circle = new Circle(5.0), and then call circle.calculateArea(). 

To summarize, static methods are associated with the class itself and can be accessed without creating objects, while non-static methods are associated with instances of the class and require object creation to access them.