类里面的接口 [英] Interface inside Class

查看:189
本文介绍了类里面的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Q1。我可以在java中的类中有一个接口?



Q2。我可以在接口中有一个类吗?



如果是,那么在这种情况下应该使用这样的类/接口。

解决方案

Q1。是Q2。是的。




  • 在您的类中,您可能需要多个接口实现,这只与这个特定的类相关。在这种情况下,使其成为内部接口,而不是公共/包私有的。


  • 在您的界面中,您可以定义一些数据库类




后者的一个例子:

  public interface EmailService {

void send(EmailDetails details);

class EmailDetails {
private String from;
private String to;
private string messageTemplate;
// etc ...
}
}


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.

解决方案

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...
    }
}

这篇关于类里面的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆