如何使数据成员只能由类和子类访问 [英] How to make data member accessible to class and subclass only

查看:48
本文介绍了如何使数据成员只能由类和子类访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
为什么Java中没有子类可见性修饰符?

Java的访问级别表,显示4个不同的选项来控制对类成员的访问:

The access level table for Java, shows 4 different options for controlling access to members of a class:

Modifier    Class  Package Subclass World
public      Y      Y       Y        Y
protected   Y      Y       Y        N
no modifier Y      Y       N        N
private     Y      N       N        N

但是,没有用于仅类和子类可访问"的修饰符.那就是:

There is no modifier, however, for "accessible to class and subclass only". That is:

Modifier    Class  Package Subclass World
c++prot     Y      N       Y        N

是否完全可以在Java中定义这种访问级别?

Is it possible at all to define such access level in Java?

如果是,怎么办?

如果这不可能,那必须归因于精心设计的原则.如果是这样,那是什么原则.换句话说,为什么在Java中具有这样的访问级别不是一个好主意?

If this isn't possible, this must be due to a well thought design principle. If so, what is that principle. In other words, why having such access level in Java isn't a good idea?

推荐答案

设计原则是开发人员不要恶意入侵自己的程序.如果您不信任同一包中的类不能正确运行,那么您将遇到严重的非技术性问题恕我直言.

The design principle is that developers do not maliciously hack their own programs. If you don't trust classes in the same package to behave correctly you have serious non-technical issues IMHO.

访问修饰符用于限制意外错误,它们试图以最小的复杂度阻止大多数错误.

The access modifiers are there to restrict accidental errors, and they attempt to stop most error with minimum complexity.

BTW:通过反射/JNI调用,您可以绕过所有访问修饰符,因此它们不是坚如磐石的安全措施恕我直言.

BTW: with reflection/JNI calls you can bypass all access modifiers, so they are not a rock solid security measure IMHO.

这篇关于如何使数据成员只能由类和子类访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆