类属性声明:私人与公开 [英] Class attribute declaration: private vs public

查看:125
本文介绍了类属性声明:私人与公开的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是定义一个私有属性,而不是公共属性的优势是什么?为什么我要创造方法的额外的工作来访问和修改属性士兵如果我可以让他们公开?

What are the advantages of defining a private attribute instead of a public attribute? Why should I have the extra work of creating methods to access and modify privates attributes if I can just make them public?

推荐答案

如果您使用的getter / setter方法​​可以在变更或访问执行逻辑。你可以验证输入,而不是假设它总是正确的。你可以跟踪的价值有多少次是牵强。

If you use getters/setters you can perform logic upon changes or access. You could validate input, instead of assuming it is always correct. You could track how many times the value is fetched.

最重要的是,这是很好的设计。它给你的类的开发者,在如何使用它更多的控制和更大的能力,以prevent误用,滥用,或只是有人做错了什么。

Most of all, it's good design. It gives you, the developer of the class, more control over how it is used and a greater ability to prevent misuse, abuse, or just someone doing something wrong.

这篇关于类属性声明:私人与公开的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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