DEV Community

Pavithra C
Pavithra C

Posted on

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;
    }
}

Enter fullscreen mode Exit fullscreen mode
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");
    }
}

Enter fullscreen mode Exit fullscreen mode

🔹** Example 2: Getter for boolean type**

public class Light {
    private boolean isOn;

    // Getter
    public boolean isOn() {
        return isOn;
    }

    // Setter
    public void setOn(boolean state) {
        isOn = state;
    }
}

Enter fullscreen mode Exit fullscreen mode
public class Main {
    public static void main(String[] args) {
        Light l = new Light();
        l.setOn(true);
        System.out.println("Is light on? " + l.isOn());
    }
}

Enter fullscreen mode Exit fullscreen mode

** Example 3: Class with multiple getters**

public class Book {
    private String title;
    private String author;
    private int pages;

    public String getTitle() {
        return title;
    }

    public String getAuthor() {
        return author;
    }

    public int getPages() {
        return pages;
    }

    public void setTitle(String t) {
        title = t;
    }

    public void setAuthor(String a) {
        author = a;
    }

    public void setPages(int p) {
        pages = p;
    }
}

Enter fullscreen mode Exit fullscreen mode
public class Main {
    public static void main(String[] args) {
        Book b = new Book();
        b.setTitle("The Alchemist");
        b.setAuthor("Paulo Coelho");
        b.setPages(208);

        System.out.println("Book Title: " + b.getTitle());
        System.out.println("Author: " + b.getAuthor());
        System.out.println("Pages: " + b.getPages());
    }
}

Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
payilagam_135383b867ea296 profile image
Payilagam

Good Blog! Understood setter as well! Good!