default keyword in Java
- Details
- Written by Nam Ha Minh
- Last Updated on 25 August 2019   |   Print Email
This article helps you understand how the default keyword is used in Java with code examples.
Basically, there are 3 places you can use the default keyword in Java:
- Specify the default value in a switch case statement
- Declare default values in a Java annotation
- Declare default method in an interface
Let’s see some code examples that use the default keyword.
In the following method, the default keyword is used in as switch case statement to return the default value for other 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; } }
In the following example, the default keyword is used to declare default value for a method in a custom annotation class:
public @interface Editable { boolean value() default false; String name() default "Untitled"; }
And lastly, the default keyword is used to declare a default method in an interface. For example:
public interface Animal { public void eat(); public void move(); public default void sleep() { // implementation goes here... } }
The purpose of default method is to add new methods to an interface that will not break the existing subtypes of that interface.
See all keywords in Java.
Related Tutorials:
Other Recommended Tutorials:
- 9 Rules about Constructors in Java
- 12 Rules and Examples About Inheritance in Java
- 12 Rules of Overriding in Java You Should Know
- 10 Java Core Best Practices Every Java Programmer Should Know
- Understand Interfaces in Java
- Understand abstraction in Java
- Understand encapsulation in Java
- Understand inheritance in Java
- Understand polymorphism in Java
Comments