Instance Methods vs Static Methods
Instance methods belong to an object and can access instance variables. They are called on a specific object. Static methods belong to the class itself and cannot access instance variables directly. This section focuses on instance methods.
Accessors and Mutators (Getters and Setters):
Accessors (getters) retrieve the value of a private field. Mutators (setters) update the value of a private field, often with validation. These methods follow the JavaBeans naming convention.
public class Person {
private String name;
// Accessor (getter)
public String getName() {
return name;
}
// Mutator (setter)
public void setName(String name) {
this.name = name;
}
}
Method Overriding and toString():
Method overriding allows a subclass to provide a specific implementation of a method already defined in its superclass. A common method to override is toString(), which returns a string representation of an object.
Example: Rectangle Class
public class Rectangle {
private double length;
private double width;
// Constructor
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
// Accessors
public double getLength() { return length; }
public double getWidth() { return width; }
// Mutators
public void setLength(double length) { this.length = length; }
public void setWidth(double width) { this.width = width; }
// Instance method: calculate area
public double calculateArea() {
return length * width;
}
// Instance method: calculate perimeter
public double calculatePerimeter() {
return 2 * (length + width);
}
// Instance method: check if square
public boolean isSquare() {
return length == width;
}
// Override toString()
@Override
public String toString() {
return "Rectangle[" + length + " x " + width + "]";
}
public static void main(String[] args) {
Rectangle rect = new Rectangle(5.0, 3.0);
System.out.println("Area: " + rect.calculateArea());
System.out.println("Perimeter: " + rect.calculatePerimeter());
System.out.println("Is Square? " + rect.isSquare());
}
}
Key Points:
- Instance methods operate on an object's state; they are called on an instance, not on the class.
- Getters and setters follow the
getFieldName() / setFieldName() naming convention.
- Override
toString() to provide a meaningful text representation of your objects.
- Method overriding lets subclasses customize inherited behavior.