Java Class Methods
In Java, methods define the behavior of a class. While attributes represent
an object’s data (state), methods specify the actions that object can
perform. Every method is declared inside a class and executed when
called.
Declaring a Method in Java
A method consists of:
- Access modifier (public, private, etc.)
- Return type (void, int, String, etc.)
- Method name
- Parameters (optional)
- Method body
Example: Simple Class Method
public class Message {
static void showMessage() {
System.out.println("Welcome to Java
programming!");
}
public static void main(String[] args) {
showMessage(); // method
call
}
}
Output
Welcome to Java programming!
A static method belongs to the class and can be called directly without
creating an object.
Calling Methods Using an Object
Non-static methods belong to objects, so you must create an instance of
the class to call them.
Example: Object Method Calls
public class Bike {
public void start() {
System.out.println("Bike
started");
}
public void setSpeed(int speed) {
System.out.println("Current speed: " +
speed + " km/h");
}
public static void main(String[] args) {
Bike myBike = new Bike(); // create
object
myBike.start();
// call method
myBike.setSpeed(80);
// call method with parameter
}
}
Output
Bike started
Current speed: 80 km/h\
Key Concepts Explained
- Class creation: Bike defines behavior
- Methods: start() and setSpeed() perform actions
- Object creation: new Bike()
- Method call: myBike.start()
- Parameter passing: set Speed (80)
The dot (.) operator is used to access an object’s methods and
attributes.
Using Methods Across Multiple Classes
In real-world applications, classes are usually separated. One class
defines functionality, and another class runs the program.
File: Calculator.java
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public int square(int n) {
return n * n;
}
}
File: App.java
public class App {
public static void main(String[] args) {
Calculator calc = new
Calculator();
System.out.println("Sum: " + calc.add(7,
5));
System.out.println("Square: " +
calc.square(6));
}
}
Output
Sum: 12
Square: 36
Compile and Run Multiple Classes
When files are in the same folder:
javac Calculator.java
javac App.java
java App