009-002-008

Getter/Setter: Person Class

Easy

Problem Description

Getter/Setter: Person class

In this problem, you will create a program that implements a Person class with getter/setter methods to safely access private fields, reads name and age from standard input, sets the values, and displays them to standard output.

Learning Objective: Understand how to safely access private fields using getter/setter methods

Overview

Create a Person class representing person information. Define name and age as private fields and access them through getter/setter methods.

Specifications

  • Define following in Person class
    • private String name field
    • private int age field
    • public void setName(String name) method
    • public String getName() method
    • public void setAge(int age) method
    • public int getAge() method
  • Execute following in main method
    • Use Scanner to read name (line 1) and age (line 2) from standard input
    • Create Person instance
    • Set values with setName(), setAge() using the read values
    • Get values with getName(), getAge() and output

Input Format

name
age

Output Format

Name: name
Age: age

Ready to Try Running Code?

Log in to access the code editor and execute your solutions for this problem.

Don't have an account?

Sign Up