Loading lessons...
Class Methods
Class Methods
Class methods are functions that belong to a class. They define the behavior of objects created from the class.
Static vs non-static
- A static method belongs to the class and can be called without creating an object.
- A non-static (instance) method belongs to an object and needs an object to be called.
Static method
public class Main {
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}
public static void main(String[] args) {
myStaticMethod(); // call without an object
}
}
Non-static method
public class Main {
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}
public static void main(String[] args) {
Main myObj = new Main();
myObj.myPublicMethod(); // call with an object
}
}
When to use each
| Kind | Called how | Example |
|---|---|---|
| static | MethodName() | math helpers |
| non-static | object.method() | object behavior |
TL;DR
- Static methods belong to the class.
- Instance methods belong to objects.
- Static methods can be called without an object.