[英]Using abstract/super class for class's internal workings. Good practice wrt Access Modifiers
如何更改错误的c#-ish设计以在Java中使用明智的访问保护?
这是我的超级班
abstract class Parent {
protected parentVariable;
protected parentMethod() {
//These methods and variables contain internal workings of my sub-classes
//to avoid repetition
// I don't want classes elsewhere in the package (that don't inherit from class) to see these.
}
}
我有共享内部工作的子类,但我将其保留在超类中。 它仍然对其他类隐藏,并且可由子类使用。 等等,不:这不是c#,这是java。
Protected(c#) != Protected(java) ≈≈ Internal(C#).
c# protected = Access is limited to the containing class or types derived from the containing class.
java protected = Access is limited to the current package
Everything in the package can see access these. That's far too permissive for these internal workings.
我该如何解决? 我是否必须将共享代码归为子类,并使用“私有”,以代码重复为代价? 首先,我对父类的使用是否设计不好? 我是否必须将这些继承树放到新程序包中?
没有访问修饰符允许对子类但对同一包的类可见。
但这不是一个大问题,因为给定包中的类应该是“朋友”,可以合作并且可以同时被释放。
即使他们看到了不应使用的某些字段和方法,程序包的其他类也不属于您无法控制的任何外部API的一部分,并且受保护的方法也无法由外部代码访问。
因此,只需记录下来,就不应使用这些方法和字段,以免您或您的同事错误地使用它们。 或者,如果您确实担心同一个程序包的可见性,请将其放在自己的程序包中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.