java中如何访问类中的字段,java-子类中的私有字段可在超类中访问

它是用JLS编写的(请参见第8.3节):

“子类可以访问超类的私有字段,例如,如果

两个类都是同一个类的成员.然而,私有领域永远不会

由子类继承.”

你能举这个例子的例子吗?

我知道我们可以写:

public class MyClass {

private int x = 1;

public void testExample(MyClass m) {

m.x = 2;

}

}

在这里,我们访问私有字段m.x,但此处没有“超级类”-“子类”.

解决方法:

谈论嵌套类-这是一个示例:

public class Test {

public static void main(String[] args) {

new Subclass(10).foo();

}

static class Superclass {

private int x;

Superclass(int x) {

this.x = x;

}

}

static class Subclass extends Superclass {

Subclass(int x) {

super(x);

}

public void foo() {

Superclass y = this;

System.out.println(y.x);

}

}

}

Otherwise, the member or constructor is declared private, and access is permitted if and only if it occurs within the body of the top level class (§7.6) that encloses the declaration of the member or constructor

在这里,x的使用位于Test的主体之内,Test的主体是封闭x声明的顶级类…尽管如果您尝试使用不合格的x或仅使用this.x,那将失败…正是因为x不实际上不是继承的(按照您引用的规范).

标签:java,jls

来源: https://codeday.me/bug/20191119/2038991.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值