java不同包的子类_关于java:为什么受保护的实例成员在不同包的子类中不可见,但受保护的类成员却不可见?...

本问题已经有最佳答案,请猛点这里访问。

package one;

public class A {

protected int first;

protected static int second;

}

package two;

import one.A;

public class B extends A {

public void someMethod() {

this.first = 5; //works as expected

B.second = 6; //works

A a = new A();

// a.first = 7; does not compile

//works just fine, but why?

a.second = 8;

A.second = 9;

}

}

为什么对静态字段没有相同的限制,其背后的想法是什么?

从JLS 6.6.2:

A protected member or constructor of an object may be accessed from outside the package in which it is declared only by code that is responsible for the implementation of that object.

从6.6.2.1开始:

Let C be the class in which a protected member is declared. Access is permitted only within the body of a subclass S of C.

this.first = 5;之所以有效,是因为B是A的实现者。

A.second之所以有效,是因为此限制仅针对对象的成员定义。 B.second也是如此。

至于为什么要这样指定,您必须问定义规范的人员-我们只能做假设。 6.6.2.1甚至有一个示例,它表达与以下内容类似的问题:

Consider this example, where the points package declares:

package points;

public class Point {

protected int x, y;

void warp(threePoint.Point3d a) {

if (a.z > 0)  // compile-time error: cannot access a.z

a.delta(this);

}

}

and the threePoint package declares:

package threePoint;

import points.Point;

public class Point3d extends Point {

protected int z;

public void delta(Point p) {

p.x += this.x;  // compile-time error: cannot access p.x

p.y += this.y;  // compile-time error: cannot access p.y

}

public void delta3d(Point3d q) {

q.x += this.x;

q.y += this.y;

q.z += this.z;

}

}

A compile-time error occurs in the method delta here: it cannot access the protected members x and y of its parameter p, because while Point3d (the class in which the references to fields x and y occur) is a subclass of Point (the class in which x and y are declared), it is not involved in the implementation of a Point (the type of the parameter p). The method delta3d can access the protected members of its parameter q, because the class Point3d is a subclass of Point and is involved in the implementation of a Point3d.

我建议检查为什么我们不应该在Java中使用protected static。

protected的语义针对实例成员-protected static与protected的目的相矛盾,这可能就是为什么它没有以相同的方式受到限制的原因。

嗨,我还没有答案,受保护的静态变量如何访问? 在这种情况下,a.second = 8; 可以访问

@ nagendra547限制仅是实例成员的集合; 班级成员没有以这种方式受到限制。 规范仅对此实例成员要求。

好吧,如果B没有扩展A,那么您将无法访问类成员,例如a.second。

@ nagendra547 6.6.2.1中所述:"让C为声明受保护成员的类。仅允许在C的子类S的体内进行访问。" -由于B是A的子类,因此可以访问受保护的成员。 6.6.2强制执行实例成员的限制。 两种不同的合同。 仅当B与A在同一程序包中时,B仍可以访问A.second,而无需扩展。

我不得不说,这与执行业务有关,措辞很差。 的成员会更好很多,也更加简单。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值