关于何时使用私有域和受保护域的困惑 [英] Confusion on when to use private vs protected fields

查看:152
本文介绍了关于何时使用私有域和受保护域的困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have seen users in SO saying that protected fields are bad, because it can introduce problems as the code grows. Please refer to the following code.

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

//getters and setters

}

如果Car类由名为ToyotaCar的类扩展

If the Car class is extended by a class named ToyotaCar

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

我希望我的ToyotaCar对象有一个 modelName yearReleased 字段。这就是我决定延续Car class的原因。但私有成员不是由子类继承的(即使我可以使用公共getter和setter访问这些字段)。现在我的困惑在于我是否应该将Car类中的文件保护为保护而不是私有。但人们说这会引入问题。

I want my ToyotaCar object to have a modelName and yearReleased fields. And that is why I decided to extend from Car class. But private members are not inherited by the subclass (even though I could access those fields using a public getter and setter). Now my confusion is whether I should make the fileds in the Car class to protected instead of private. But people say that introduces problems.

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

Does it mean no matter what class you write always, make the fields private?

如果是,那么使用protected关键字的实例是什么?它只适用于我们计划在子类中使用的方法吗?

If so on what instances the protected keyword is used? is it only for methods which we are planning to use in our subclasses?

推荐答案

你自己钉了它:一个好的做法是默认情况下使一切都私密。然后,您的特定设计可能需要例如能够使用某些属性或(最好)子类内的某些方法。在这种情况下,你需要将它们移向'受保护' - 但仅限于那种情况。

You nailed it yourself: a good practice is to make everything 'private' by default. Then, your specific design may require for example to be able to use some attributes or (preferably) some methods inside a subclass. In that situation, you'll need to move them toward 'protected' - but only in that situation.

请记住,使用访问者(getters& setters)是完美的好的,可以在不破坏封装的情况下完成。

Remember that using the accessors (getters & setters) is perfectly ok, and can be done without breaking encapsulation.

这篇关于关于何时使用私有域和受保护域的困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆