007-004-007

Method Definition: Greeting Method

Easy

Problem Description

Method Definition: Greeting Method

In this problem, you will design a Greeter class with a name field, constructor, greeting method, and name getter.

Learning Objective: Understand how to define fields, constructors, and methods within a class, implementing behavior that depends on object state

Overview

Create a Greeter class with a constructor that accepts a name, a sayHello method that displays a greeting using that name, and a getName method that returns the name.

Specifications

  • Define a private String name field in Greeter class
  • Constructor Greeter(String name) initializes the name
  • sayHello() method: prints "Hello, name!" to standard output (void method)
  • getName() method: returns the name

Output Example

Greeter g = new Greeter("World");
g.sayHello();       // → Hello, World!
g.getName();        // → World

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