Java 什么';不使用protected处理抽象类的正确方法是什么?
例如:Java 什么';不使用protected处理抽象类的正确方法是什么?,java,android,abstract-class,protected,Java,Android,Abstract Class,Protected,例如: public abstract class SomeBaseClass extends Fragment { protected static final String INT_TAG = "int_tag"; protected int someInt; //... } public class ChildClass extends SomeBaseClass { public static ChildClass newInstance(int argIn
public abstract class SomeBaseClass extends Fragment {
protected static final String INT_TAG = "int_tag";
protected int someInt;
//...
}
public class ChildClass extends SomeBaseClass {
public static ChildClass newInstance(int argInt) {
Bundle args = new Bundle();
bundle.putInt(INT_TAG, argInt);
ChildClass fragment = new ChildClass();
fragment.setArgs(args);
return fragment;
}
public void onCreate() {
someInt = getArguments().getInt(INT_TAG);
}
//...
}
然而,我听说出于某种原因(我不知道为什么),在抽象类中使用受保护的变量是个坏主意。另一种选择是什么?访问受保护的属性是个坏主意,因为它破坏了封装,使您的应用程序强耦合。仍然可以使用getter和setter访问受保护的字段
访问受保护的属性是个坏主意,因为它破坏了封装,使您的应用程序强耦合。仍然可以使用getter和setter访问受保护的字段
受保护的成员变量违反了OOP的主要原则:封装(又称信息隐藏)。但是简单地将它们设置为私有并添加(受保护的)getter/setter方法并不会改变它。此外,继承常常被错误地用于代码重用,因为它在(抽象)基类中声明了真正属于扩展类的变量,而不需要在每个子类中声明它们。所以我能说的最好的话就是:始终在真正使用变量的类中声明变量
private
。@TimothyTruckle抽象类和private不能一起工作well@javaguy对我来说,它工作得很好。这里令人敬畏的讨论受保护的成员变量违反了OOP的主要原则:封装(又称信息隐藏). 但是简单地将它们设置为私有并添加(受保护的)getter/setter方法并不会改变它。此外,继承常常被错误地用于代码重用,因为它在(抽象)基类中声明了真正属于扩展类的变量,而不需要在每个子类中声明它们。所以我能说的最好的话就是:始终在真正使用变量的类中声明变量private
。@TimothyTruckle抽象类和private不能一起工作well@javaguy对我来说,这一切都很完美。这里的讨论太棒了