The difference between Java static methods and instance methods

Static methods and instance methods are two common method types in Java. They have some important differences in functionality and use. This article details these differences and provides corresponding source code examples.

  1. Definition
    : Static methods are methods that belong to a class and can be called directly through the class name without creating an instance of the class. They are typically used to perform class-related tasks, such as utility methods or calculating values ​​unrelated to class properties.

Instance Methods are methods that belong to instances of a class and must be called by creating an instance object of the class. They can access and manipulate instance variables and are often used to perform instance-related tasks.

  1. How to call
    Static methods can be called directly through the class name, ClassName.staticMethod()e.g. They do not depend on an instance object of the class, so they can be called without creating an instance.

Instance methods must be called by creating an instance object of the class, ClassName instance = new ClassName(); instance.instanceMethod()e.g. Instance methods are only accessible through the instance object because they depend on the instance's state and properties.

Here is an example that demonstrates how to call static and instance methods:

public class MyClass {
   
    
    
    public static

Guess you like

Origin blog.csdn.net/DevAstro/article/details/133505541