Home >Java >javaTutorial >How do Java functions compare? How are they different?
There are two types of Java functions: static methods and instance methods. Static methods do not require object instances, are called directly through the class name, and are used to perform operations unrelated to the class state. Instance methods require an object instance to be called and are used to access or modify the state of the object.
Java Function Comparison
In Java, there are two types of functions: static methods and instance methods. They have different purposes and usages as follows:
Static method (class method)
static
keyword Code example:
public class MathUtils { public static int add(int a, int b) { return a + b; } public static void main(String[] args) { int result = MathUtils.add(5, 10); System.out.println(result); // 输出:15 } }
Instance method
static
Keyword declaration##Code example:
public class Person { private String name; public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public static void main(String[] args) { Person p1 = new Person("John"); p1.setName("Mary"); System.out.println(p1.getName()); // 输出:Mary } }
Main differences
Static methods | Instance methods | |
---|---|---|
Not required | Required | |
Class name.methodName() | object.methodName() | |
Operation independent of the object | Access or modify the state of the object | |
Accessible from anywhere | Accessible only from within the same instance |
Practical case
Write a static method to splice any two strings:
public class StringUtils { public static String concat(String str1, String str2) { return str1 + str2; } public static void main(String[] args) { String name1 = "John"; String name2 = "Doe"; String fullName = StringUtils.concat(name1, name2); System.out.println(fullName); // 输出:JohnDoe } }
The above is the detailed content of How do Java functions compare? How are they different?. For more information, please follow other related articles on the PHP Chinese website!