017-003-007
Default and Static Methods
Medium
Problem Description
Default and static Methods
In this problem, you will create a program that defines default and static methods in a Loggable interface, and demonstrates how implementing classes can use the default method as-is or override it, displaying the results to standard output.
Learning Objective: Understand how to define and distinguish between default methods and static methods in interfaces, introduced in Java 8
Overview
Define default and static methods in a Loggable interface, and write a program that demonstrates both using the default method as-is and overriding it.
Specifications
Loggable interface
- Declare abstract method
String getTag()(defined by implementing classes) - Define default method
default void log(String message)that prints in the format"[{getTag()}] {message}" - Define static method
static void info(String message)that prints in the format"[INFO] {message}"
AppLogger class (implements Loggable)
getTag()method returns"APP"- Uses the default log() method without overriding
DebugLogger class (implements Loggable)
getTag()method returns"DEBUG"- Overrides
log()to print in the format">>> [{getTag()}] {message} <<<"
Main class
- Call
Loggable.info("System started")(static method) - Create an
AppLoggerinstance and calllog("User logged in") - Create a
DebugLoggerinstance and calllog("Variable x = 42")
Output Format
[INFO] System started
[APP] User logged in
>>> [DEBUG] Variable x = 42 <<<
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