a method is a block of code within a class that defines a specific behavior or action an object can perform.
it encapsulates functionality and can operate on an object’s data fields or external inputs.
components -
return type - specifies what a method return. ex - void, int, etc.
method name - descriptive identifier (function name)
parameters - optional inputs
body - code that executes when method is called.
class Rectangle {
int length;
int width;
// Method to calculate area
int calculateArea() {
return length * width;
}
// Method to set dimensions
void setDimensions(int l, int w) {
length = l;
width = w;
}
}
public class Main {
public static void main(String[] args) {
Rectangle rect = new Rectangle();
rect.setDimensions(5, 3);
int area = rect.calculateArea(); // Returns 15
System.out.println("Area: " + area);
}
}
a static method belongs to a class rather than an instance of the class.
it can be called without creating an object.
declared with static keyword
class MathUtils {
// Static method
static int square(int num) {
return num * num;
}
}
public class Main {
public static void main(String[] args) {
int result = MathUtils.square(4); // No object needed
System.out.println("Square: " + result); // Outputs: Square: 16
}
}
it is a special method used to initialize objects when they are are created.
it sets an initial state of an object’s field.
has the same name as the class.
no return type
called automatically.
typically public but can be private.
class Book {
String title;
int pages;
// Constructor
Book(String title, int pages) {
this.title = title; // this distinguishes field from parameter
this.pages = pages;
}
void display() {
System.out.println("Title: " + title + ", Pages: " + pages);
}
}
public class Main {
public static void main(String[] args) {
Book book = new Book("Java Basics", 300);
book.display(); // Outputs: Title: Java Basics, Pages: 300
}
}