Other classes similar to OptionalInt
are OptionalDouble
, OptionalLong
, and Optional
.
These help us eliminate exceptions that occur due to the absence of a value at runtime.
The key is to first check if the Optional contains a value before trying to retrieve it.
Default Method in Java
What are default methods?
Java 5
interface Java5Interface {
public static int four = 4;
int five = 5; // implicitly public static
public abstract void welcome();
public void sayHi();
void bye();
}
interface Java5Invalid {
private int six = 6; //illegal only public static and final is permitted
private void cleanuup(); // illegal only public and abstract is permitted
}
Java 8 and onwards
interface Greetings {
public default void greet() {
openDoor();
sayHi();
sayBye();
closeDoor();
}
default void openDoor() {
//open the door
}
void sayHi();
void sayBye();
private void closeDoor() {
lockDoor();
}
static void lockDoor() {
//lock door implementation
}
}
- default methods are public.
- default methods are inherited by implementation classes.
- default methods can be overridden by implementation classes.
- a default method can add more functionality to the Interface without breaking binary compatibility.
- static methods are also allowed which are Interface level methods and cannot be overridden by subclasses.
- Java 8 methods can have public, private, abstract, default, static, and strictfp.