问题描述
因为静态东西在类加载时加载,甚至可以在创建对象之前作为ClassName.member
Since static things loaded at time of class loading,and can be used even before object creation as ClassName.member
但是如果静态方法是私有的,那么你只能在类中做这件事 ClassName.method()
也可以直接访问 method()
而无需附加类名.
but if static method is private,so you can only do this thing ClassName.method()
inside class which is also accessible by directly method()
without appending classname.
因此使 private
方法 static
没有意义,直到它没有被用于同一类的任何 static
方法.因为只有私有不能在同一个类的其他静态方法中使用.
Hence making a private
method static
has no significance untill it is not being used in any static
method of same class.since only private can not be use in some other static method of same class.
但我看到一些方法没有在任何其他静态东西中使用,但它们仍然是static
.例如ArrayList
hugeCapacity方法>-
But I seen some method those are not being use in any other static stuff and still they are static
.For Example hugeCapacity
method of ArrayList
-
private static int hugeCapacity(int minCapacity) {...}
为什么我们不只将其保密?
private int hugeCapacity(int minCapacity) {...}
能否让我知道背后的意义,在我们的 Java 库中将此方法设为静态?
Can one let me know significance behind, making this method static in our java Libraries?
推荐答案
进行这种区分(不是强制性的)可以为班级的客户传达一种意义,并提示他们的行为.
Making this distinction (that is not mandatory) conveys a meaning for clients of the class and gives hints on their behavior.
private int hugeCapacity(int minCapacity) {...}
假设方法行为取决于当前实例.所以客户端类期望它可以操作实例成员和可选地静态成员.
supposes that the method behavior depends on the current instance.So the client class expects that it may manipulate instance members and optionally static members.
虽然这个
private static int hugeCapacity(int minCapacity) {...}
假设方法行为是一个与特定实例无关的类方法.因此它可以仅操作静态成员.
supposes that the method behavior is a class method that is not related to a specific instance. So it can manipulate only static members.
这不是一个很好的优化,但它节省了一个额外的参数,由 JVM 传递给每个方法.
您在源代码中看不到它,但是对于实例方法,this
确实是作为参数添加到编译代码中的.
It is not a great optimization but it spares an additional parameter that is passed to each method by the JVM.
You don't see it in the source code but for instance methods, this
is indeed added in the compiled code as parameter.
这篇关于为什么私有静态方法存在那些没有在任何静态上下文中被调用的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!