简体   繁体   English

Java中使用静态方法和实例方法的方式有何不同?

[英]What is the difference in the way static methods and instance methods are used in Java.

While reading a book, i came across this statement: 在读一本书时,我遇到了这样的说法:


The methods of an object define its behaviour. 对象的方法定义其行为。 These methods are called instance methods. 这些方法称为实例方法。 It is important to note that these methods pertain to each object of the class. 重要的是要注意,这些方法与类的每个对象有关。 This should not be confused with the implementation of the methods which is shared by all instances of the class. 这不应与该类的所有实例共享的方法的实现混淆。


I know what instance methods are, I know what static methods are (ie shared by all instances of the class). 我知道什么是实例方法,我知道什么是静态方法(即由该类的所有实例共享)。 The above statement seem to suggest that the implementation of the methods is shared by all instances. 上面的陈述似乎表明所有实例都共享方法的实现。 What exactly does this mean? 这到底是什么意思? It doesnt sound like it is refering to static methods. 听起来好像不是在引用静态方法。

It means that you don't get an extra copy of the code itself alongside each instance of the class. 这意味着您不会在类的每个实例旁边获得额外的代码本身副本。 The behaviour is associated with an instance of the class, so it has that context , but there's no extra "per instance" price to pay in terms of memory etc for instance methods. 该行为与该类的实例相关联,因此它具有该上下文 ,但是对于实例方法在内存等方面没有额外的“每实例”代价。

One quick point to note about static : I don't like the description of it being "shared by all instances of the class" as that suggests that if there aren't any instances, it's unusable. 关于static一个简短的注意点:我不喜欢将其描述为“由类的所有实例共享”,因为这表明如果没有任何实例,则它是不可用的。 I prefer to say that it's associated with the class itself instead of a specific instance of the class. 我更喜欢说它与类本身相关联,而不是与类的特定实例相关联。

Instances share implementations, but implementations act on single instances. 实例共享实现,但是实现作用于单个实例。

  • "these methods pertain to each object of the class" - method acts on single instances. “这些方法与类的每个对象有关” -方法作用于单个实例。
  • "implementation of the methods which is shared by all instances" - there's only one implementation of the method. “由所有实例共享的方法的实现” -该方法只有一种实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM