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");
}
}
🔹** 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;
}
}
public class Main {
public static void main(String[] args) {
Light l = new Light();
l.setOn(true);
System.out.println("Is light on? " + l.isOn());
}
}
** 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;
}
}
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());
}
}
Top comments (1)
Good Blog! Understood setter as well! Good!