Core Java

Getters and Setters Java Example

Hello readers! In this tutorial, we feature a comprehensive Getters and Setters in Java example. We will learn the Accessor and Mutator in Java programming language.

1. Introduction

Java programming offers Accessor and Mutator or popularly called as Getter and Setter methods that are used to update the variable values and retrieve them. The following class illustrates the private variables and the setter/getter methods of those variables.

Employee.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// Employee class.
class Employee {
    // Member variables of the class.
    private int id;
    private String name;
    private String designation;
    private String company;
    public int getId() {
        return id;
    }
    public void setId(final int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(final String name) {
        this.name = name;
    }
    public String getDesignation() {
        return designation;
    }
    public void setDesignation(final String designation) {
        this.designation = designation;
    }
    public String getCompany() {
        return company;
    }
    public void setCompany(final String company) {
        this.company = company;
    }
}

Note: By Java convention,

  • Getter methods,
    • Start with ‘get’ keyword followed by the variable name with the first letter of the variable as capitalized
    • Return the attribute value
  • Setter methods,
    • Start with ‘set’ keyword followed by the variable name with the first letter of the variable as capitalized
    • Take an argument and assign it the member variable

1.1 Why do developers use Setter and Getter methods?

The use of setter and getter methods allow developers to validate and control the value initialization and access. Let us understand this with an example,

1
2
3
4
5
6
7
8
public void setName(final String name) {
    // Validating the name and throwing an exception if name is null or length is <= 0.
    if(name == null ||  name.length() <= 0) {
        throw new IllegalArgumentException();
    }
    this.name = name;
}

This validation ensures that the name variable always meets the validation criteria. Here, Encapsulation played a crucial role by hiding the member variables of a class (i.e. making them private) from the outside world. Thus, the setter method protects the variable value from unexpected changes by the caller code and the getter method is the only way for the outside world that reads the variable’s value.

1
2
3
public String getName() {
    return name;
}

To start with the captioned tutorial, we are hoping that users at present have their preferred Ide installed on their machines. For easy usage, I am using Eclipse Ide on a Windows operating system.

2. Getters and Setters Java Example

We’ll demonstrate the use of setter and getter methods in Java. For a better understanding, developers can execute the below code in Eclipse Ide.

2.1 Example with Setter & Getter

In this example, we will understand the importance of encapsulation and the usage of setter/getter methods in Java.

AppMain.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.jcg.example;
// Employee class.
class Employee {
    // Member variables of the class.
    private int id;
    private String name;
    private String designation;
    private String company;
    public int getId() {
        return id;
    }
    public void setId(final int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(final String name) {
        // Validating the name and throwing an exception if name is null or length is <= 0.
        if(name == null ||  name.length() <= 0) {
            throw new IllegalArgumentException();
        }
        this.name = name;
    }
    public String getDesignation() {
        return designation;
    }
    public void setDesignation(final String designation) {
        this.designation = designation;
    }
    public String getCompany() {
        return company;
    }
    public void setCompany(final String company) {
        this.company = company;
    }
    // 'toString()' method to print the values.
    @Override
    public String toString() {
        return "Employee: [id= " + getId() + ", name= " + getName() + ", designation= " + getDesignation() + ", company= " + getCompany() + "]";
    }
}
// Main class.
public class AppMain {
    public static void main(String[] args) {
        // Creating the employee object.
        final Employee myemployee = new Employee();
        // Setting the employee details via the setter methods.
        myemployee.setId(1001);
        myemployee.setName("James");
        myemployee.setDesignation("Software Developer");
        myemployee.setCompany("ABC Corporation");
        // Printing the employee details via the 'toString()' method that uses the getter methods.
        System.out.println(myemployee.toString());
    }
}

If everything goes well, the following output will be printed in the Ide console. Make note, the exception will be thrown if the name variable value is null or empty.

Output

1
Employee: [id= 1001, name= James, designation= Software Developer, company= ABC Corporation]

2.2 Example without Setter & Getter

In this example, we will see that if a developer doesn’t make the setter/getter methods then Java encapsulation throws a compile-time exception as the variables are marked as ‘private’.

AppMainWithoutSetterGetters.java

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.jcg.example;
// Employee class.
class NewEmployee {
    // Member variables of the class.
    // As per Java specification the member variables of a POJO class is always marked as 'private'.
    // Making them 'public' will expose the class data which is against the Java specification.
    private int id;
    private String name;
    private String designation;
    private String company;
    public NewEmployee() {  }
    public NewEmployee(int id, String name, String designation, String company) {
        this.id = id;
        this.name = name;
        this.designation = designation;
        this.company = company;
    }
}
// Main class.
public class AppMainWithoutSetterGetters {
    public static void main(String[] args) {
        // Creating the employee object.
        final NewEmployee myemployee = new NewEmployee();
        myemployee.id = 1001;                           // Error! The Employee class's id field is private.
        myemployee.name = "James";                      // Error! The Employee class's name field is private.
        myemployee.designation = "Software Developer"// Error! The Employee class's designation field is private.
        myemployee.company = "ABC Corporation";         // Error! The Employee class's company field is private.
    }
}

That is all for this tutorial and I hope the article served you whatever you were looking for. Happy Learning and do not forget to share!

3. Conclusion

In this tutorial, we learned the importance of setter/getter methods in Java. Developers can download the sample application as an Eclipse project in the Downloads section.

4. Download the Eclipse Project

This was an example of Setter and Getter methods in the Java programming language.

Download
You can download the full source code of this example here: Getters and Setters Java Example

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
RAHUL Mourya
RAHUL Mourya
2 years ago

we use this.name

note – that is not complsary to use this word , you can try without this and the program run properly without error , you should not use this because its will make program more complicated.

Back to top button