In Java 8, default methods appeared in the interfaces, and you can crank something like this:
interface Foo { // интерфейс default Foo foo() { // его метод foo с реализацией по-умолчанию, который должен вернуть экземпляр интерфейса class Bar { // локальный класс Bar в методе foo public Foo bar() { // метод bar класса Bar return new Foo() { // возвращаем экземпляр анонимной реализацию интерфейса }; } } return new Bar().bar(); // создаем экземпляр локального класса Bar, вызываем метод bar и возвращаем то, что он вернул } } public class Baz implements Foo { // класс Baz, унаследованный от Foo (а значит у него есть метод foo) public static void main(String[] args) { // отсюда стартует программа Baz myBaz = new Baz(); // создаем экземпляр класса Baz Foo myFoo = myBaz.foo(); // вызываем на нем метод foo ,который вернет нам анонимный экземпляр Foo, созданный методом bar класса Bar } }
Comments:
Why do you put in front of the bar and foo "Foo" methods?
This is the type of return value. Any method must either return something or be void .
and the last line is essentially the creation of an instance of "Foo" - "myFoo"?
Yes exactly.
create an interface with one method and implement it, what's this? in this case, is its implementation the creation of a local class and the return of its instance? or by "implement" it means the interface, and does the class "Baz"?
Creating a single method interface Foo is the declaration interface Foo and Foo foo() .
You can implement it either in a specific class ( Baz ) or in the default method in the interface itself.
In this case, its implementation is the default implementation in the default Foo foo() method.
The Baz class, which implements the Foo interface due to the default implementation of the foo() method, is needed so that you can create an object to which the foo() method can be called.