Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Default Methods | Interface
course content

Зміст курсу

Java OOP

Default MethodsDefault Methods

Abstract class vs Interface: The Interface Strikes Back!

Previously, methods with implementations could only exist in abstract classes, but starting from Java 8, they also appeared in interfaces.

A default method is a method with an implementation within an interface. Implementation classes can also use or override them when needed.

Let's take a look at the syntax for declaring a default method:

We need default methods for the same purposes as regular methods in Java. We use them when we need an implementation in the method and when we want to implement only the interface without additional classes. Let's consider a small example using default methods:

java

Main.java

In this example, the interface Greeting contains a default method sayHello() with a default implementation. The class GreetingImpl implements this interface and overrides the greet() method. In the main method, an instance of GreetingImpl is created and both methods are called.

What is the purpose of a default method in a Java interface?

Виберіть правильну відповідь

Все було зрозуміло?

Секція 3. Розділ 4
course content

Зміст курсу

Java OOP

Default MethodsDefault Methods

Abstract class vs Interface: The Interface Strikes Back!

Previously, methods with implementations could only exist in abstract classes, but starting from Java 8, they also appeared in interfaces.

A default method is a method with an implementation within an interface. Implementation classes can also use or override them when needed.

Let's take a look at the syntax for declaring a default method:

We need default methods for the same purposes as regular methods in Java. We use them when we need an implementation in the method and when we want to implement only the interface without additional classes. Let's consider a small example using default methods:

java

Main.java

In this example, the interface Greeting contains a default method sayHello() with a default implementation. The class GreetingImpl implements this interface and overrides the greet() method. In the main method, an instance of GreetingImpl is created and both methods are called.

What is the purpose of a default method in a Java interface?

Виберіть правильну відповідь

Все було зрозуміло?

Секція 3. Розділ 4
some-alt