java接口能是private,Java 9接口private方法

在Java 9中, 我们可以在接口内创建私有方法。接口允许我们声明私有方法, 这些方法有助于在非抽象方法之间共享通用代码。

在Java 9之前, 在接口内创建私有方法会导致编译时错误。以下示例使用Java 8编译器进行编译, 并引发编译时错误。

Java 9专用接口方法示例

interface Sayable{

default void say() {

saySomething();

}

// Private method inside interface

private void saySomething() {

System.out.println("Hello... I'm private method");

}

}

public class PrivateInterface implements Sayable {

public static void main(String[] args) {

Sayable s = new PrivateInterface();

s.say();

}

}

输出:

PrivateInterface.java:6: error: modifier private not allowed here

注意:要实现私有接口方法, 请仅使用Java 9或更高版本来编译源代码。

现在, 让我们使用Java 9执行以下代码。看到输出, 它可以正常执行。

Java 9专用接口方法示例

interface Sayable{

default void say() {

saySomething();

}

// Private method inside interface

private void saySomething() {

System.out.println("Hello... I'm private method");

}

}

public class PrivateInterface implements Sayable {

public static void main(String[] args) {

Sayable s = new PrivateInterface();

s.say();

}

}

输出:

Hello... I'm private method

这样, 我们也可以在接口内创建私有静态方法。请参见以下示例。

Java 9私有静态方法示例

interface Sayable{

default void say() {

saySomething(); // Calling private method

sayPolitely(); // Calling private static method

}

// Private method inside interface

private void saySomething() {

System.out.println("Hello... I'm private method");

}

// Private static method inside interface

private static void sayPolitely() {

System.out.println("I'm private static method");

}

}

public class PrivateInterface implements Sayable {

public static void main(String[] args) {

Sayable s = new PrivateInterface();

s.say();

}

}

输出:

Hello... I'm private method

I'm private static method

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值