The default
keyword in Java serves various purposes across different contexts, offering flexibility and enhancing code readability. Here, we explore three key scenarios where the default
keyword is employed:
Consider the following method, where the default
keyword is utilized within a switch case statement to provide a default value for unspecified cases:
public static int getDaysOfMonth(int month) {
switch (month) {
case 2:
return 28;
case 4:
case 6:
case 9:
case 11:
return 30;
default:
return 31;
}
}
This method efficiently returns the number of days in a month, defaulting to 31 for cases not explicitly handled.
In the next example, the default
keyword is used within a custom annotation class to declare default values for annotation attributes:
public @interface Editable {
boolean value() default false;
String name() default "Untitled";
}
This Editable
annotation showcases default values for boolean and String attributes, providing a fallback when not explicitly specified.
The default
keyword also finds utility in interfaces, allowing the declaration of default methods. In the interface example below, a default method sleep()
is added:
public interface Animal {
void eat();
void move();
default void sleep() {
// Implementation goes here...
}
}
The primary purpose of a default method in an interface is to introduce new methods without breaking existing subtypes.
By understanding the diverse applications of the default
keyword, Java developers gain a powerful tool for managing switch cases, custom annotations, and interface evolution.