java中private,static,final,public,abstract关键字的使用模式 [英] Usage patterns for private, static, final, public, abstract keywords in java

查看:136
本文介绍了java中private,static,final,public,abstract关键字的使用模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除了抽象之外,我知道所有这些所做的事情。我目前正在自学java,我认为是一个中学阶段的教育(我的高中是在一个坏邻居,所以我得到了轴)...

I know what all of these do except for abstract. I'm currently in the process of teaching myself java with what I consider a middle-school-level education (my highschool was in a bad neighborhood so I got shafted)...

但这些关键字的使用模式究竟是什么?我什么时候用?我什么时候省略它们?将'public'放在我的类前面使得每个使用它的类都需要一个新文件,如果我想创建一个单片源文件,我可以省略它吗?

But what exactly are the usage patterns for these keywords? When do I use what? When do I omit them? Putting 'public' in front of my classes makes every class that uses it require a new file, can I just omit that if I want to create a monolithic source file?

我查阅的每一点信息都准确地解释了这些信息的作用,但没有清楚地说明何时/为何/我应该使用它们。

Every bit of information I look up, explains exactly WHAT these do, just doesn't give a clear view of when/why/where I should use them.

谢谢提前,
Anthony

Thanks in advance, Anthony

推荐答案

初学者,这是我的经验法则:

For beginners, here are my rules of thumb:


  1. 公开:所有类都应该公开(这不是真的,但它非常接近)。对于方法,请考虑一下您的电视机:您希望对电视进行的操作是公开的。

  2. 私有:实施细节应该是私密的。想想你的电视机:如果电视的同类物品应该是私人的,那么功能就是私密的,因为用户可以永久地弄乱电视,触电等等。

  3. 受保护的:现在忽略这一点。

  4. 摘要:我在学习Java时读到的最好的例子就是思考鸟。鸟是抽象的,因此会有一个抽象的飞行方法。个别鸟类知道如何飞行(除非它们是企鹅 - 然后它们抛出UnsupportedOperationException)。

  1. Public: all classes should be public (this isn't quite true, but it's pretty close). For methods, think about your TV set: stuff you'd expect to do to your TV is "public".
  2. Private: implementation details should be private. Think about your TV set: functionality is private if the equivalent kind of thing for a TV should be private, because the user can mess the TV up permanently, get electrocuted, etc.
  3. Protected: ignore this for now.
  4. Abstract: The best example I read when learning Java was to think about "Bird". Bird is abstact, and therefore would have an "abstract" flight method. Individual species of bird know how to fly (unless they're penguins - then they throw UnsupportedOperationException).

我强烈建议你打架使用一个单片源文件的冲动。尝试保持方法短于一个屏幕,并且类别短于300行。

I would strongly suggest you fight the urge to use one monolithic source file. Try to keep methods shorter than one screenful, and classes shorter than 300 lines.

这篇关于java中private,static,final,public,abstract关键字的使用模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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