Day-22:Encapsulation and getter method

What is getter method ? In Java, a getter method is a method used to access (or get) the value of a private field (variable) from outside the class. It is a part of encapsulation, which is one of the four main principles of object-oriented programming. Why use getter methods? Java encourages keeping class variables private for security and control. To access these private variables from outside the class, getter methods (and sometimes setter methods) are used. Key Points: The method name usually starts with get followed by the variable name with the first letter capitalized. It returns the value of the private field. There is no parameter in a getter method. Example 1: Getter for int type public class Car { private int speed; // Getter public int getSpeed() { return speed; } // Setter public void setSpeed(int newSpeed) { speed = newSpeed; } } public class Main { public static void main(String[] args) { Car c = new Car(); c.setSpeed(120); System.out.println("Car speed: " + c.getSpeed() + " km/h"); } }

Apr 16, 2025 - 08:17
 0
Day-22:Encapsulation and getter method

What is getter method ?
In Java, a getter method is a method used to access (or get) the value of a private field (variable) from outside the class. It is a part of encapsulation, which is one of the four main principles of object-oriented programming.

Why use getter methods?

  • Java encourages keeping class variables private for security and control.
  • To access these private variables from outside the class, getter methods (and sometimes setter methods) are used.

Key Points:

  • The method name usually starts with get followed by the variable name with the first letter capitalized.
  • It returns the value of the private field.
  • There is no parameter in a getter method.

Example 1: Getter for int type

public class Car {
    private int speed;

    // Getter
    public int getSpeed() {
        return speed;
    }

    // Setter
    public void setSpeed(int newSpeed) {
        speed = newSpeed;
    }
}

public class Main {
    public static void main(String[] args) {
        Car c = new Car();
        c.setSpeed(120);
        System.out.println("Car speed: " + c.getSpeed() + " km/h");
    }
}