事情为什么会设置为私有?我不打算去疯了,乱用随机变量 [英] Why sets things to private? I'm not going to go crazy and mess with random variables

查看:81
本文介绍了事情为什么会设置为私有?我不打算去疯了,乱用随机变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不认为我理解为什么设置一些私人除你应该这样做。如果我有一台自动售货机类,它有一个变量,说有多少硬币它在机,这是没用的一切,为什么要我将它设置为私有?它不象我要得到高,而在另一个类写vendingMachine.coins = 99999

I don't think I'm understanding why setting something to private other than "you should just do it". If I had a vending machine class and it has a variable that says how many coins it has in the machine which is useless to everything else, why should I set it to private? It's not like I'm going to get high and in another class write vendingMachine.coins = 99999.

推荐答案

这可能是真实的,但在面向对象的一点是要区分责任,并保持数据以及相应的方法。对于非常小的和一个人的项目,这可能不是必要的,但是在你从其他人重用的对象有时你会不知道哪个字段,你应该修改,哪些不应该与混乱的大项目。这就是为什么在OOP中只定义了接口,公众和所有内部的东西专用。这也可以让你以后改变内部实现,而不破坏你的计划。

That's probably true, but the point in OOP is to separate responsibilities and to keep data together with the corresponding methods. For very small and one man projects this might not be necessary, but in big projects where you reuse objects from other people you will sometimes not know which fields you should modify and which should not be messed with. That's why in OOP you define only the interface public and all internal stuff private. That also allows you to change the internal implementation later without breaking your program.

看一看: http://simple.wikipedia.org/wiki/OOP

这篇关于事情为什么会设置为私有?我不打算去疯了,乱用随机变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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