Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interface inside Class

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/interfaces used.

like image 511
Amol Ghotankar Avatar asked Oct 07 '11 14:10

Amol Ghotankar


1 Answers

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...
    }
}
like image 113
Bozho Avatar answered Sep 30 '22 13:09

Bozho