Java Encapsulation: Implementing Person Class with Getter and Setter Methods
Write a Java program to create a class called Person with private instance variables name, age. and country. Provide public getter and setter methods to access and modify these variables.
Sample Solution:
Java Code:
Output:
Name: Arthfael Viktorija Age: 25 Country: US
Explanation:
In the above exercise, the Person class encapsulates the private instance variables name, age, and country. These variables are declared private, which means they cannot be accessed outside the Person class.
To access and modify these private variables, public getter and setter methods are provided. The getter methods (getName(), getAge(), and getCountry()) allow other classes to retrieve the values of private variables. The setter methods (setName(), setAge(), and setCountry()) provide a way to modify the values of private variables.
In the Main class, an instance of the Person class is created using the Person constructor (Person person = new Person()). Then, the setter methods are used to set the values of the private variables name, age, and country.
To retrieve these values, the getter methods are called (String name = person.getName(), int age = person.getAge(), String country = person.getCountry()). Finally, the retrieved values are printed using System.out.println().
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program where the "Person" class includes a method to validate if the age is above 18.
- Write a Java program where the "Person" class adds a method to display the full name in uppercase.
- Write a Java program where the "Person" class restricts setting an empty name.
- Write a Java program where the "Person" class tracks nationality changes with a history list.
Go to:
Java Code Editor:
Improve this sample solution and post your code through Disqus
PREV : Java Encapsulation Exercises Home.
NEXT : Implementing the BankAccount Class with Getter and Setter Methods.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.