Questions tagged [default-method]

A default method is a feature introduced in Java 8 which allows an interface to declare a method body. Classes which implement the interface are not required to override a default method. Use this tag for questions relating to default methods.

A default method is a feature introduced in which allows an interface to declare a method body. Classes which implement the interface are not required to override a default method. An interface method is made default by adding the default keyword, also introduced in Java 8.

In the following example, then method is a default method of the Command interface.

@FunctionalInterface
interface Command {

    void execute();

    default Command then(Command next) {
        return () -> {
            this.execute();
            next.execute();
        };
    }

}

Adding a default method to an interface or changing a method from abstract to default does not break compatibility with a pre-existing binary if the binary does not attempt to invoke the method.

See also:

168 questions
-3
votes
2 answers

why default method not recognized as property(getter/setter)?

Interface: public interface SomeInt{ Integer getX(); void setX(Integer value); default Integer getY(){ return getX(); } default void setY(Integer value){ setX(value); } } A Class implement it: public class A…
brallow
  • 49
  • 3
-4
votes
2 answers

How to access child's field from the interface in Java?

Java 8 introduced "default method" which allows describing the method's body. I want to create one Interface and two child classes. In the Interface URL I'd like to have getURL() method: public interface URL { int getURL() { return…
Павел Иванов
  • 1,863
  • 5
  • 28
  • 51
-4
votes
1 answer

How to simulate static variable in Java interface default method?

To easily enable logging for plurality of my project classes, I have decided to abuse the new default keyword to create a simple method trait for my classes: default void Log(Level lvl, String msg) { Logger log =…
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
1 2 3
11
12