Recall & Review
beginner
What is a getter method in Java?
A getter method is a public method that returns the value of a private variable. It allows controlled access to the variable from outside the class.
Click to reveal answer
beginner
What is a setter method in Java?
A setter method is a public method that sets or updates the value of a private variable. It allows controlled modification of the variable from outside the class.
Click to reveal answer
beginner
Why do we use getter and setter methods instead of making variables public?
Getter and setter methods protect the data by controlling how variables are accessed or changed. This helps keep the data safe and allows adding checks or rules when getting or setting values.
Click to reveal answer
beginner
Show a simple example of a getter and setter for a private variable 'age' in Java.
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
Click to reveal answer
intermediate
Can setter methods include validation? Give an example.
Yes, setter methods can check values before setting them. For example, to ensure age is not negative:
public void setAge(int age) {
if (age >= 0) {
this.age = age;
} else {
System.out.println("Age cannot be negative.");
}
}
Click to reveal answer
What does a getter method do?
✗ Incorrect
A getter method returns the value of a private variable to allow read access.
Why use setter methods instead of making variables public?
✗ Incorrect
Setter methods allow control and validation when changing variable values.
Which keyword is used inside a setter to refer to the current object's variable?
✗ Incorrect
The keyword 'this' refers to the current object's variable inside methods.
What is the typical access level of getter and setter methods?
✗ Incorrect
Getter and setter methods are usually public to allow access from outside the class.
Which of these is a valid setter method signature for a variable 'name' of type String?
✗ Incorrect
A setter method returns void and takes a parameter of the variable's type.
Explain what getter and setter methods are and why they are important in Java.
Think about how to safely access and change private data.
You got /5 concepts.
Write a simple Java class with a private variable and add getter and setter methods for it, including validation in the setter.
Use if statement inside setter to check values.
You got /5 concepts.