java连接不到接口_java – “___()___()在___中被定义在不可访问的类或接口”编译错误...

我发现一个奇怪的编译限制,我不能解释,我不明白这个限制的原因。

实施例-1:

考虑这些类:

在包e1中:

public class C1 {

enum E1 { A, B, C }

public E1 x;

}

在包e2中:

import e1.C1;

public class C2 {

public String test(C1 c1) {

return c1.x.toString(); // here compilation error

}

}

这会导致以下编译错误:

Error:(5,20) java: toString() in java.lang.Enum is defined in an inaccessible class or interface

实施例-2:

考虑这些类:

在包i1中:

public interface I1 {

int someMethod();

}

public class C1 {

static class I2 implements I1 {

public int someMethod() {

return 1;

}

}

public I2 x = new I2();

}

在包i2中:

import i1.C1;

import i1.I1;

public class C2 {

public static void main(String[] args) {

C1 c1 = new C1();

System.out.println(c1.x.someMethod()); // compilation error

}

}

这也导致相同的编译错误,但是如果我们将违规行更改为:

System.out.println(((I1)c1.x).someMethod());

然后可以编译并正常工作。

所以问题是:

为什么这种对辅助功能的限制需要?

是的,我明白示例1中的C1.E类和示例2中的C1.I2)是私有的。但同时很明显,没有人可以为基础接口(Object of Object)的方法分配较弱的访问权限,因此将对象直接转换到其基本接口并访问受限方法将始终是安全的。

有人可以解释这个限制的目的和原因吗?

A member (class, interface, field, or method) of a reference (class, interface, or array) type or a constructor of a class type is accessible only if the type is accessible…

看来这是限制,但不能解释为什么需要这个限制(在上述例子中)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值