017-004-006

Default Methods in Interfaces

Medium

Problem Description

Default Methods in Interfaces

In this problem, you will create a program that defines a default method in the Greetable interface, uses it in the Person class without overriding, and displays greeting messages to standard output.

Learning Objective: Understand default methods in interfaces and use them in implementing classes

Overview

Since Java 8, interfaces can define "default methods". Default methods have implementations within the interface, and implementing classes can use them without overriding.

Specifications

Complete the following interface and implementing class:

  1. Greetable interface:

    • void greet() - abstract method
    • default void greetWithTime() - default method (outputs "Good morning!")
  2. Person class:

    • Implements Greetable
    • Field: String name
    • constructor: Person(String name)
    • Implement greet(): output "Hello, I'm [name]"
    • Use greetWithTime() without overriding
  3. Main class:

    • Create a Person object and call both greet() and greetWithTime()

Output Format

Hello, I'm Alice
Good morning!

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