Methods (instance methods)
Methods define the behavior of an object. They can access and modify instance variables.
Syntax:
returnType methodName(parameterList) { // method body}Example:
class Rectangle { double width, height;
double calculateArea() { return width * height; }
void setDimensions(double w, double h) { width = w; height = h; }}Calling methods:
Rectangle rect = new Rectangle();rect.setDimensions(5, 10);double area = rect.calculateArea();Method modifiers:
public,private,protected– access controlstatic– belongs to classabstract– no body, must be overriddenfinal– cannot be overriddensynchronized– thread‑safe
Return types:
- Primitive or reference type
void– no return value
Parameters: Passed by value (for primitives) or reference (objects).