Shadow variable used in default method for interface in Java 8

Today I was thinking of a good way to write less code for the general functionality needed for different objects.

Inheritance can do the job, but then the classes cannot inherit from anyone else, so I chose the interfaces.

So, I have an interface with functionality that I will need for some objects:

public interface Test {
    String message = "Hello from Interface!";

    default void printMessage() {
        System.out.println(message);
    }
}

And then I can use it in any object without having to redefine / write any code more than just calling the method if necessary:

public class TestingTest implements Test {

    public String message = "Hello from Class!";

    public TestingTest() {
        printMessage();
    }

    public static void main(String[] args) {
        new TestingTest();
    }
}

! ... , , , (), , -, , , , ( ).

, , printMessage , , , ? - ?

.

+4
1

String message static (AFAIK). .

- () :

default void printMessage(String... messages) {
    if (messages.length == 0) {
        messages = new String[] { "arrgg" };
    }
    System.out.println(messages[0]);
}

, ,

public String message() { return "..."; }
+3

Source: https://habr.com/ru/post/1614289/


All Articles