Initialize classes in their own interface

qt0 :

I looked at some code and noticed such construction:

public interface TestIntrerface {
  void doFirst();
  void doSecond();
}

public interface Interface1 extends TestIntrerface {
  Interface1 inter = new FirstClass();
}

public interface Interface2 extends TestIntrerface {
  Interface2 intr = new SecondClass();
}


public class FirstClass implements Interface1 {
  public void doFirst() {
    //...
  }

   public void doSecond() {
      //...
   }
}

public class SecondClass implements Interface2 {
   public void doFirst() {
      //...
   }

  public void doSecond() {
      //...
  }
}


public class Test {
  public static void main(String[] args) {
    Interface1.inter.doFirst();
    Interface2.intr.doSecond();
  }
}

It has the potential for me but I've never seen that construct before. Two questions:

  1. What is the name of this pattern (is that pattern(?))?
  2. It is a good practice to use this in the real world?
Andrew Tobilko :

It's an example of two constant declarations inter and intr in interfaces. It's not a pattern and I wouldn't say it's a good practice.

  1. Interface1 and Interface2 are meaningless: they don't complement/implement the interfaces they extend. Basically, they are holders of the constants that could have been defined somewhere else. Note that the constants are bound to particular classes while interfaces carry a broader sense, provide a general interface.

  2. The names inter and intr are terrible and they don't tell what those constants represent/do.

A more justifiable example would look like

interface TestInterface {
  void doFirst();
  void doSecond();

  TestInterface EMPTY = new TestInterface() {
    @Override
    public void doFirst() {}
    @Override
    public void doSecond() {}
  };

}

where EMPTY tells that it's a default (and empty) implementation of the interface. Notice that I called it EMPTY (not empty) because it's always a public static final field.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=307662&siteId=1