0
0
Javaprogramming~30 mins

Getter and setter methods in Java - Mini Project: Build & Apply

Choose your learning style9 modes available
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
Need a 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
Need a 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
Need a 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
Need a 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.