Interface inside class

Q1. Can I have an interface inside a class in java?

Q2. Can I have a class inside an interface?

If so, in what situations should such classes / interfaces be used.

+6
source share
2 answers

Q1. Yes Q2. Yes.

  • Inside your class, you may need several implementations of the interface, which applies only to this class. In this case, make it an internal interface, not a public / batch one.

  • In your interface, you can define some classes of data holders that will be used by implementations and clients.

One example of the latter:

public interface EmailService { void send(EmailDetails details); class EmailDetails { private String from; private String to; private String messageTemplate; // etc... } } 
+9
source

I came across the provision of common complex operations for all classes that implement an interface that explicitly use interface operations.

Until Java 8 comes out ...

See http://datumedge.blogspot.hu/2012/06/java-8-lambdas.html (Default Methods)

Workaround for this:

 public interface I { public Class U{ public static void complexFunction(I i, String s){ if(); ig(s) } } } 

Then you can easily call the general functionality (after importing the IU)

 U.complexFunction(i,"my params..."); 

It can be further refined, with more typical coding:

 public interface I { public Class U{ I me; U(I me){ this.me = me; } public void complexFunction(String s){ me.f(); me.g(s) } } U getUtilities(); } class implementationOfI implements I{ U u=new U(this); U getUtilities(){ return u; } } 

then

 I i = new implementationOfI(); i.getUtilities().complexFunction(s); 

Further sharp tricks

  • provides U as an abstract, enabling local implementation of certain functions for U ...
  • overriding U with a local class and local constructor using I.this instead of forcing the parameter to pass ...
  • using static U ... however then every operation should get i i as a parameter ...
  • using enum instead of a class for static functions that do not require additional objects (equivalent to the first method)

The reason for this is to put operations in a single module instead of having utility modules hanging around, which extends the worst duplicated implementation.

+2
source

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


All Articles