Jump into concepts and practice - no test required
or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Getter and Setter Methods
π Scenario: You are creating a simple Java class to represent a Book in a library system. Each book has a title and a number of pages. You want to control access to these details using getter and setter methods.
π― Goal: Build a Java class called Book with private fields for title and pages. Then create getter and setter methods to access and update these fields safely. Finally, create an instance of Book and display its details.
π What You'll Learn
Create a class named Book with private fields title (String) and pages (int).
Add a getter method getTitle() that returns the book's title.
Add a setter method setTitle(String title) to update the book's title.
Add a getter method getPages() that returns the number of pages.
Add a setter method setPages(int pages) to update the number of pages.
Create a main method to create a Book object, set its title and pages, and print them.
π‘ Why This Matters
π Real World
Getter and setter methods are used in real-world Java programs to control how data inside objects is accessed and changed, protecting the data from accidental or harmful changes.
πΌ Career
Understanding getters and setters is essential for Java developers because it helps write clean, safe, and maintainable code, which is a key skill in software development jobs.
Progress0 / 4 steps
1
Create the Book class with private fields
Create a class called Book with two private fields: String title and int pages.
Java
Hint
Use the private keyword before the field types to hide them from outside the class.
2
Add getter and setter methods for title
Add a getter method called getTitle() that returns title, and a setter method called setTitle(String title) that sets the title field.
Java
Hint
Getter methods return the field value. Setter methods take a parameter and assign it to the field using this.
3
Add getter and setter methods for pages
Add a getter method called getPages() that returns pages, and a setter method called setPages(int pages) that sets the pages field.
Java
Hint
Follow the same pattern as the title getter and setter, but for the pages field.
4
Create main method to test getters and setters
Add a main method inside the Book class. Inside it, create a Book object called myBook. Use setTitle("Java Basics") and setPages(250) to set its fields. Then print the title and pages using getTitle() and getPages().
Java
Hint
Create the main method with public static void main(String[] args). Then create the object and use the setter and getter methods to set and print the values.
Practice
(1/5)
1. What is the main purpose of getter and setter methods in Java?
easy
A. To create new objects from a class
B. To control access to private variables by reading and updating their values
C. To perform arithmetic operations on variables
D. To print values directly to the console
Solution
Step 1: Understand the role of getters and setters
Getters and setters are methods used to access and modify private variables safely.
Step 2: Identify their purpose in encapsulation
They help protect data by controlling how variables are read or changed from outside the class.
Final Answer:
To control access to private variables by reading and updating their values -> Option B
Hint: Setter methods are void and assign parameter to this.variable [OK]
Common Mistakes:
Using return type int for setter
Assigning instance variable to parameter instead of reverse
Making setter private
3. What will be the output of the following code?
public class Person {
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public static void main(String[] args) {
Person p = new Person();
p.setName("Alice");
System.out.println(p.getName());
}
}
medium
A. Alice
B. null
C. Compilation error
D. Empty line
Solution
Step 1: Trace the setter method call
The setName method sets the private variable name to "Alice".
Step 2: Trace the getter method call
The getName method returns the value of name, which is now "Alice".
Final Answer:
Alice -> Option A
Quick Check:
Setter sets "Alice", getter returns "Alice" [OK]
Hint: Setter sets value, getter returns it [OK]
Common Mistakes:
Expecting null because variable is private
Thinking code causes compilation error
Assuming output is empty line
4. Identify the error in this setter method and choose the correct fix:
public void setScore(int score) {
score = score;
}
medium
A. Remove parameter from method
B. Change method return type to int
C. Make method private
D. Use this.score = score; to assign parameter to instance variable
Solution
Step 1: Understand variable shadowing
The parameter score shadows the instance variable score, so score = score; assigns parameter to itself.
Step 2: Fix assignment using this
Use this.score = score; to assign the parameter value to the instance variable.
Final Answer:
Use this.score = score; to assign parameter to instance variable -> Option D
Quick Check:
Use this.variable = parameter to fix shadowing [OK]
Hint: Use this.variable to avoid shadowing in setters [OK]
Common Mistakes:
Assigning parameter to itself
Changing return type incorrectly
Making setter private unnecessarily
5. You have a class with a private int field temperature. You want to ensure the temperature can only be set between 0 and 100. Which setter method correctly enforces this rule?
hard
A. public void setTemperature(int temperature) { if (temperature < 0 || temperature > 100) this.temperature = 0; else this.temperature = temperature; }
B. public void setTemperature(int temperature) { this.temperature = temperature; }
C. public int setTemperature(int temperature) { if (temperature > 0) this.temperature = temperature; return temperature; }
D. public void setTemperature(int temperature) { if (temperature >= 0 && temperature <= 100) this.temperature = temperature; }
Solution
Step 1: Understand the requirement
The setter must only allow values between 0 and 100 inclusive.
Step 2: Analyze each option
public void setTemperature(int temperature) { if (temperature >= 0 && temperature <= 100) this.temperature = temperature; } sets temperature only if in range but does nothing if out of range (temperature remains unchanged). public void setTemperature(int temperature) { if (temperature < 0 || temperature > 100) this.temperature = 0; else this.temperature = temperature; } sets temperature to 0 if out of range, enforcing a default safe value.
Step 3: Choose the best enforcement
public void setTemperature(int temperature) { if (temperature < 0 || temperature > 100) this.temperature = 0; else this.temperature = temperature; } actively prevents invalid values by resetting to 0, ensuring temperature is always valid.
Final Answer:
public void setTemperature(int temperature) { if (temperature < 0 || temperature > 100) this.temperature = 0; else this.temperature = temperature; } -> Option A
Quick Check:
Setter enforces range with else and default value [OK]
Hint: Use if-else to enforce valid range in setter [OK]