Java Class Methods
Class methods in Java are functions defined within a class that describe the behaviors or actions that objects of the class can perform. Methods can manipulate the object's attributes and provide a way to interact with the object's data.
1. Defining Methods
Methods are defined inside the class body and include an access modifier, return type, method name, and parameters (if any).
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
2. Calling Methods
Methods are called using the dot notation on an object of the class.
Calculator calc = new Calculator();
int result = calc.add(5, 10);
System.out.println("Result: " + result); // Outputs: Result: 15
3. Static Methods
Static methods belong to the class rather than any instance. They can be called without creating an object of the class.
public class MathUtil {
public static int square(int number) {
return number * number;
}
}
int squared = MathUtil.square(4);
System.out.println("Squared: " + squared); // Outputs: Squared: 16
4. Method Overloading
Methods can be overloaded by defining multiple methods with the same name but different parameters.
public class Display {
public void show(int number) {
System.out.println("Number: " + number);
}
public void show(String text) {
System.out.println("Text: " + text);
}
}
5. Access Modifiers
Access modifiers control the visibility of methods:
public
: Accessible from any other class.private
: Accessible only within the declared class.protected
: Accessible within the same package or subclasses.default
(no modifier): Accessible within the same package.
Key Takeaways
- Class methods define the behaviors of objects.
- Methods can manipulate object attributes and perform operations.
- Static methods belong to the class and can be called without creating an object.
- Method overloading allows for flexible method definitions.
- Use access modifiers to control method visibility and encapsulation.