inner class in interface

本文探讨了在Java接口中定义类的特性和优势,此类自动成为公共静态成员,仅存在于接口的命名空间内。通过示例展示了如何在接口内放置一个实现该接口的类,并在主方法中调用其方法进行测试。此外,讨论了将测试代码置于嵌套类中的方法,以避免测试代码在最终产品中暴露。

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

Any class we put inside an interface is automatically public and static. Since the class is static, the nested class is only placed inside the namespace of the interface.

// innerclasses/ClassInInterface.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// {java ClassInInterface$Test} // note, cd innerclasses to use this command

public interface ClassInInterface {
  void howdy();

  class Test implements ClassInInterface {
    @Override
    public void howdy() {
      System.out.println("Howdy!");
    }

    public static void main(String[] args) {
      new Test().howdy();
    }
  }
}
/* Output:
Howdy!
*/

When we  put a main() in every class to act as a test bed for that class. A potential drawback is that our test fixtures are exposed in our shipping product. If this is a problem, we can use a nested class to hold our test code:

// innerclasses/TestBed.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
// Putting test code in a nested class
// {java TestBed$Tester} // we must escape the $ under Unix/Linux systems

public class TestBed {
  public void f() {
    System.out.println("f()");
  }

  public static class Tester {
    public static void main(String[] args) {
      TestBed t = new TestBed();
      t.f();
    }
  }
}
/* Output:
f()
*/

references:

1. On Java 8 - Bruce Eckel

2. https://github.com/wangbingfeng/OnJava8-Examples/tree/master/innerclasses

3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/innerclasses/TestBed.java

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值