java java中private、static、final、public、abstract关键字的使用模式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5083232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:19:18  来源:igfitidea点击:

Usage patterns for private, static, final, public, abstract keywords in java

javakeywordverbosity

提问by ThantiK

I know whatall 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)...

除了抽象之外,我知道所有这些都做了什么。我目前正在通过我认为的中学教育自学 Java(我的高中在一个糟糕的社区,所以我被甩了)......

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?

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

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.

我查找的每一点信息都准确地解释了它们的作用,只是没有清楚地说明我应该何时/为什么/在哪里使用它们。

Thanks in advance, Anthony

提前致谢,安东尼

采纳答案by James Kingsbery

For beginners, here are my rules of thumb:

对于初学者,以下是我的经验法则:

  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).
  1. 公共:所有类都应该是公共的(这并不完全正确,但非常接近)。对于方法,请考虑您的电视机:您希望对电视机执行的操作是“公开的”。
  2. 私有:实现细节应该是私有的。想想您的电视机:如果电视的等效事物应该是私密的,那么功能就是私密的,因为用户可能会永久弄乱电视,触电等。
  3. 受保护:暂时忽略这一点。
  4. 摘要:我在学习 Java 时读到的最好的例子是思考“Bird”。鸟是抽象的,因此会有一个“抽象”的飞行方法。个别种类的鸟类知道如何飞行(除非它们是企鹅——然后它们会抛出 UnsupportedOperationException)。

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.

我强烈建议您抵制使用单一源文件的冲动。尽量使方法短于一屏,类短于 300 行。

回答by Bozho

Sources tell what do these keywords mean because when/why/where they are used follows from that. My explanations have the "when" word, for example, but they follow directly from the semantics of the keywords.

消息来源告诉我们这些关键字的含义是什么,因为它们的使用时间/原因/地点由此而来。例如,我的解释有“when”这个词,但它们直接来自关键字的语义。

  • privateshould be used when something is not used outside of a given class
    • for methods and fields - when they are used only within the same class
    • for classes - only on nested classes, when used in the same class
  • protectedshould be used when
    • for methods and field - when you need to make them accessible to subclasses only
    • for classes - again only nested classes, accessible by subcalsses
  • publicis used when something is accessible by every other class
  • private当在给定的类之外没有使用某些东西时应该使用
    • 对于方法和字段 - 当它们仅在同一个类中使用时
    • 对于类 - 仅在嵌套类上,当在同一个类中使用时
  • protected应该在什么时候使用
    • 对于方法和字段 - 当您需要让它们只能被子类访问时
    • 对于类 - 同样只有嵌套类,可以通过子类访问
  • public当某些东西可以被其他所有类访问时使用

The above three are "visibility modifiers". They are used when you want to limit the usage of some methods/fields/classes to a group of objects, and hide them from other objects. There is another visibility modifier - the default one (when no other is present). It is used when you want your class/method/field to be accessible only to classes from the same package.

以上三个是“可见性修饰符”。当您想将某些方法/字段/类的使用限制为一组对象,并将它们隐藏在其他对象中时,将使用它们。还有另一个可见性修饰符 - 默认的(当没有其他修饰符时)。当您希望您的类/方法/字段只能由同一包中的类访问时使用它。

  • staticis used when you don't need an instance of a class (i.e. object) to use it:
    • for fields - when you want to have a global field
    • for methods - when you need utility functions that do not depend on object state
    • for nested classes - when you want to access them without an instance of the enclosing class.
  • abstractwhen you don't want to provide implementations in the current class:
    • on methods - when subclasses have to provide the actual implementation, but you want to invoke these methods (no matter how they are implemented) in this class.
    • on classes - to denote that the class may have abstract methods.
  • final- when you don't want something to change.
    • on fields, when you want to assign the value only once. It is useful when you want to pass a local variable to an inner class - you have to declare it final.
    • on classes and methods - when you don't want subclasses to be able to extend / override them.
  • static当您不需要类(即对象)的实例来使用它时使用:
    • 对于字段 - 当您想要一个全局字段时
    • 对于方法 - 当您需要不依赖于对象状态的实用函数时
    • 对于嵌套类 - 当您想在没有封闭类的实例的情况下访问它们时。
  • abstract当您不想在当前类中提供实现时:
    • 在方法上——当子类必须提供实际的实现,但你想在这个类中调用这些方法(无论它们是如何实现的)。
    • 在类上 - 表示该类可能具有抽象方法。
  • final- 当您不想改变某些事情时。
    • 在字段上,当您只想分配值一次时。当您想将局部变量传递给内部类时,它很有用 - 您必须将其声明为 final。
    • 关于类和方法 - 当您不希望子类能够扩展/覆盖它们时。

回答by wkl

Bozho has covered the uses for the keywords pretty well, but I will add that if you do not declare a scope at all, your scope becomes package-private, which means that anyone in the same package as the class can use that class/method. Basically, it's more permissive than private, but less permissive than just protected, as protectedallows access from outside a package.

Bozho 已经很好地介绍了关键字的用法,但我要补充一点,如果您根本不声明作用域,您的作用域将成为包私有的,这意味着与类位于同一包中的任何人都可以使用该类/方法. 基本上,它比 更宽松private,但比仅仅宽松protected,因为protected允许从包外部进行访问。

Information about the 'no modifier' access here:

有关此处“无修饰符”访问的信息:

I recommend going through the Java tutorial:

我建议阅读 Java 教程:

And also take a look at the book questions if you want to explore more of Java:

如果您想探索更多 Java,还可以查看本书的问题:

回答by unholysampler

private, publicand protectedare all used for declaring the Scopeof a class for variable.

private,publicprotected都用于声明变量的类的作用域

staticmeans that the thing being defined is a member of the class and not an object that is instance of the class.

static意味着被定义的事物是类的成员,而不是作为类实例的对象。

abstractmeans that the class can not directly created and can only be used by subclasses. An abstract method can be defined in an abstract class and means that any subclass must define a method matching the defined signature.

abstract意味着类不能直接创建,只能被子类使用。抽象方法可以在抽象类中定义,这意味着任何子类都必须定义与定义的签名匹配的方法。

finalmeans that the variable can only be assigned a variable once at its creation. A final class/method can not be inherited/overridden, respectively.

final意味着变量只能在创建时分配一次变量。最终的类/方法不能分别被继承/覆盖。

Stay away from putting everything in one big file. Use an IDE, like Eclipse, and it will make it easy to work with code that has one class per file. It allows you to better organize your code and encapsulate code so you don't end up in a situation where everything knows about everything. This will lead to errors as it becomes easier to accidentally use something the was created to do a different purpose.

避免将所有内容放在一个大文件中。使用 IDE(如 Eclipse),可以轻松处理每个文件具有一个类的代码。它使您可以更好地组织代码并封装代码,这样您就不会陷入一切都无所不知的境地。这将导致错误,因为更容易意外地使用创建的东西来实现不同的目的。

回答by Nahid Nisho

A privatemethod is a method which can't be accessed by any other object outside the scope it is introduced.

private法是不能用的范围之外它被引入任何其他对象进行访问的方法。

A staticmethod is a method that belongs to a class rather than an instance of a class. The method is accessible to every instance of a class, but methods defined in an instance are only able to be accessed by that member of a class.

static方法是属于一类,而不是一个类的实例的方法。类的每个实例都可以访问该方法,但实例中定义的方法只能由类的该成员访问。

The finalkeyword is used in several contexts to define an entity that can only be assigned once.

final关键字在多个上下文中用于定义只能分配一次的实体。

The publicmembers are visible to all other classes. This means that any other class can access a publicfield or method.

public成员是所有其他类可见。这意味着任何其他类都可以访问public字段或方法。

The abstractmethods don't have body, they just have method signature.If a regular class extends an abstract class, then the class must have to implement all the abstract methods of abstract parent class or it has to be declared abstract as well

abstract方法不具备的身体,他们只是有方法signature.If一个普通类扩展一个抽象类,则该类必须实现抽象父类的所有抽象方法或者它必须被声明为抽象以及

回答by Ryan Castillo

In order to understand the when/why/where of these keyword uses, you have to get a grasp on some key concepts of Object Oriented Programming and Java. I suggest looking into Encapsulationand Polymorphism.

为了理解这些关键字的使用时间/原因/地点,您必须掌握面向对象编程和 Java 的一些关键概念。我建议研究EncapsulationPolymorphism

Also off the top of my head, I believe 'public' is implied so it isn't required but its good practice to have it there.

同样在我的脑海中,我相信“公开”是隐含的,所以它不是必需的,但是将它放在那里是一种很好的做法。