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:
Greetableinterface:void greet()- abstract methoddefault void greetWithTime()- default method (outputs "Good morning!")
Personclass:- Implements
Greetable - Field:
String name - constructor:
Person(String name) - Implement
greet(): output "Hello, I'm [name]" - Use
greetWithTime()without overriding
- Implements
Mainclass:- Create a
Personobject and call bothgreet()andgreetWithTime()
- Create a
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