Interface inside Class

后端 未结 2 894
梦毁少年i
梦毁少年i 2021-01-02 18:32

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

Q2. Can I have an class inside an interface?

If yes, then in which situations should such classes/interfa

2条回答
  •  忘掉有多难
    2021-01-02 18:58

    Q1. Yes Q2. Yes.

    • Inside your class you may need multiple implementations of an interface, which is only relevant to this particular class. In that case make it an inner interface, rather than a public / package-private one

    • In your interface you can define some data holder classes that are to 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...
        }
    }
    

提交回复
热议问题