The code above defines an interface called MyInterface with a
static method called doSomething(). It then creates a class
called MyClass which implements MyInterface.
The main
method of MyClass creates an object of MyClass called obj
and invokes the doSomething() method at Line 1. This causes
a compilation error at Line 1. This
is because the code tries to
access a static interface method via an object of the class. Static
interface methods can only be accessed via the interface name.
In order to fix the error, Line 1 needs to be replaced as follows:
MyInterface.doSomething();
247.
248.
CHAPTER
07
Optionals
What is an Optional and why was it added by Java 8?
Answer:
An Optional is used to represent a value that can either be
present or absent. It has methods that
can be used to retrieve the
underlying value if present. The following code demonstrates an
Optional:
Optional
number;
So here, number is an Optional of type Integer. It may or may
not contain a value.
Optionals were added by Java 8 to avoid the boilerplate code
associated with null checks. Sometimes, a method may return a
null. This can result in a NullPointerException. In order to
avoid the exception, the code that invokes the method needs to
have explicit null checks. This can make the code difficult to read.
Java 8 Optionals help to avoid this boilerplate code. So instead of
having an explicit null check, an optional can be used. If the value
is present it can be retrieved.
Do'stlaringiz bilan baham: