1
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);
}
//...
}
不过我听说这是一个坏主意,用在抽象类中受保护的变量由于某种原因(我不知道为什么)。有什么选择?
protected成员变量,违反了面向对象的主要原理:封装(又名信息隐藏)。但简单地将它们设置为私有的并添加(受保护的)getter/setter方法不会改变它。通过在(抽象)基类中声明属于扩展类的变量,而不需要在每个子类中声明变量,继承经常被误用于代码重用。所以我能说的最好的是:总是在那个真正使用它们的类中声明你的变量'private'。 –
@TimothyTruckle抽象类和私人不能很好地合作 – developer
@javaguy对我来说,它完美的工作。 –