混淆何时使用私有字段与受保护字段

Confusion on when to use private vs protected fields

我看到 SO 中的用户说受保护的字段不好,因为随着代码的增长它会引入问题。请参考以下代码。

public class Car {
    private String modelName;
    private int yearReleased;

//getters and setters

}

如果汽车 class 由一辆名为 ToyotaCarclass 的汽车扩展

public class ToyotaCar extends Car{
   // Toyota specific stuff
}

我希望我的 ToyotaCar 对象具有 modelNameyearReleased 字段。这就是我决定从 Car class 扩展的原因。但是私有成员不会被 subclass 继承(即使我可以使用 public getter 和 setter 访问这些字段)。现在我的困惑是我是否应该将 Car class 中的文件设置为受保护的而不是私有的。但人们说这会引入问题。

这是否意味着无论 class 你总是写什么,将字段设为私有?

如果是,在什么情况下使用了 protected 关键字?它仅适用于我们计划在我们的 subclasses 中使用的方法吗?

您自己搞定了:一个好的做法是将所有内容设为默认 'private'。然后,您的特定设计可能需要例如能够在子类中使用某些属性或(最好)某些方法。在那种情况下,您需要将它们移向 'protected' - 但仅限于那种情况。

请记住,使用访问器(getter 和 setter)是完全可以的,并且可以在不破坏封装的情况下完成。

如果(由于特定的 design/pattern)更改子 class 的字段非常紧迫,那么您应该将 class 字段声明为 protected.

If not so, then generally the better approach is to perform the same using a public/protected member method in the parent class updating those private fields in the parent class and then, calling that public/protected member method from your child class' object.

这样,您可以通过从子 class' 对象调用父 class 成员方法来更新那些父 class' 私有字段来实现实现。

用于声明变量的受保护关键字用于使这些实例变量对同一包中的所有其他 classes 以及 class[sub class] 可见将扩展涉及那些受保护变量的超级class。

当然,你可以声明变量为private或protected modifiers.But 当你声明变量为private时,你可以隐藏变量,这样其他classes就无法访问直接访问它,另一方面,如果你用 protected 声明变量,那么你就是在不使用任何 getter 方法的情况下让变量直接访问它,这违反了 OOP 原则。

所以在我看来,由于 Car 是所有其他 class 的超级 class,例如 ToyotaCar,因此 on.Declare 您的超级 class 中的变量是私有的并在 sub class 中使用 getter 和 setters 方法根据您的需要进行读写。通过这样做,您就遵守了 OOP 原则。

希望这对您有所帮助。

谢谢