Java Class Methods: Defining Functions Within a Class

Explore Java class methods, which are functions defined within a class to perform specific actions. This guide will help you understand the structure and purpose of methods in Java programming, enabling you to create more organized and efficient code. Learn how to define, call, and utilize class methods effectively in your Java applications.



Java Class Methods

In Java, methods are functions defined within a class that perform specific actions.

Create a Method

To create a method, use the keyword void (indicating no return value) followed by the method name and parentheses:

Syntax

public class Main {
static void myMethod() {
System.out.println("Hello World!");
}
}
    

Call a Method

To call a method, write its name followed by parentheses within the main method:

Example

public class Main {
static void myMethod() {
System.out.println("Hello World!");
}

public static void main(String[] args) {
myMethod();
}
}
    
Output

Hello World!
    

Static vs. Public Methods

Java methods can be static (accessible without creating objects) or public (accessible through object instances):

Example

public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}

// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}

public static void main(String[] args) {
myStaticMethod(); // Call the static method

Main myObj = new Main(); // Create an object of Main
myObj.myPublicMethod(); // Call the public method on the object
}
}
    

Access Methods With an Object

To use methods defined in a class, create an object and call the methods on it:

Example

public class Main {
public void fullThrottle() {
System.out.println("The car is going as fast as it can!");
}

public void speed(int maxSpeed) {
System.out.println("Max speed is: " + maxSpeed);
}

public static void main(String[] args) {
Main myCar = new Main();   // Create a myCar object
myCar.fullThrottle();      // Call the fullThrottle() method
myCar.speed(200);          // Call the speed() method
}
}
    

Ensure Java file names match the class names for proper compilation and execution.