Why would a static inner interface be used in Java?

本文解释了静态内部接口的语义,即它与类本身而非其实例相关联,并通过示例展示了如何使用静态内部接口。此外,还探讨了将其声明为静态的原因及移除static关键字的影响。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Q:
I have just found a static inner interface in our code-base.

  1. class Foo {
  2.     public static interface Bar {
  3.         /* snip */
  4.     }
  5.     /* snip */
  6. }
复制代码

I have never seen this before. The original developer is out of reach. Therefore I have to ask SO:

What are the semantics behind a static interface? What would change, if I remove the static? Why would anyone do this?

A:
An inner interface has to be static in order to be accessed. The interface isn't associated with instances of the class, but with the class itself, so it would be accessed with Foo.Bar, like so:

  1. public class Baz implements Foo.Bar {
  2.    ...
  3. }
复制代码

In most ways, this isn't different from a static inner class.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值