【问题标题】:What's the correct way to handle abstract classes without using protected?在不使用受保护的情况下处理抽象类的正确方法是什么?
【发布时间】:2017-04-05 10:37:02
【问题描述】:

例如:

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);
    }

    //...
}

但是我听说出于某种原因在抽象类中使用受保护的变量是个坏主意(我不知道为什么)。有什么办法?

【问题讨论】:

  • 受保护的成员变量违反了 OOP 的主要原则:封装(也称为信息隐藏)。但简单地将它们设置为私有并添加(受保护的)getter/setter 方法并不会改变它。此外,通过在(抽象)基类中声明真正属于扩展类的变量而不需要在每个子类中声明它们,继承经常被滥用于代码重用。所以我能说的最好的就是:总是在真正使用它们的类中声明你的变量private
  • @TimothyTruckle 抽象类和私有不能很好地协同工作
  • @javaguy 对我来说效果很好。

标签: java android abstract-class protected


【解决方案1】:

访问受保护的属性是一个坏主意,因为它破坏了封装,使您的耦合变得强。不过,您可以使用 getter 和 setter 访问受保护的字段。

References

【讨论】:

    猜你喜欢
    • 2016-06-02
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 2020-11-02
    • 2015-08-02
    • 1970-01-01
    • 2020-04-28
    • 2011-03-26
    相关资源
    最近更新 更多