问题
I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
e.g
Obj x = new Obj();
x.someMethod
or
Obj.someMethod
(is this the static way?)
I\'m rather confused!
回答1:
One rule-of-thumb: ask yourself "does it make sense to call this method, even if no Obj has been constructed yet?" If so, it should definitely be static.
So in a class Car
you might have a method double convertMpgToKpl(double mpg)
which would be static, because one might want to know what 35mpg converts to, even if nobody has ever built a Car. But void setMileage(double mpg)
(which sets the efficiency of one particular Car) can't be static since it's inconceivable to call the method before any Car has been constructed.
(Btw, the converse isn't always true: you might sometimes have a method which involves two Car
objects, and still want it to be static. E.g. Car theMoreEfficientOf( Car c1, Car c2 )
. Although this could be converted to a non-static version, some would argue that since there isn't a "privileged" choice of which Car is more important, you shouldn't force a caller to choose one Car as the object you'll invoke the method on. This situation accounts for a fairly small fraction of all static methods, though.)
回答2:
Define static methods in the following scenarios only:
- If you are writing utility classes and they are not supposed to be changed.
- If the method is not using any instance variable.
- If any operation is not dependent on instance creation.
- If there is some code that can easily be shared by all the instance methods, extract that code into a static method.
- If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
回答3:
There are some valid reasons to use static methods:
Performance: if you want some code to be run, and don't want to instantiate an extra object to do so, shove it into a static method. The JVM also can optimize static methods a lot (I think I've once read James Gosling declaring that you don't need custom instructions in the JVM, since static methods will be just as fast, but couldn't find the source - thus it could be completely false). Yes, it is micro-optimization, and probably unneeded. And we programmers never do unneeded things just because they are cool, right?
Practicality: instead of calling
new Util().method(arg)
, callUtil.method(arg)
, ormethod(arg)
with static imports. Easier, shorter.Adding methods: you really wanted the class String to have a
removeSpecialChars()
instance method, but it's not there (and it shouldn't, since your project's special characters may be different from the other project's), and you can't add it (since Java is somewhat sane), so you create an utility class, and callremoveSpecialChars(s)
instead ofs.removeSpecialChars()
. Sweet.Purity: taking some precautions, your static method will be a pure function, that is, the only thing it depends on is its parameters. Data in, data out. This is easier to read and debug, since you don't have inheritance quirks to worry about. You can do it with instance methods too, but the compiler will help you a little more with static methods (by not allowing references to instance attributes, overriding methods, etc.).
You'll also have to create a static method if you want to make a singleton, but... don't. I mean, think twice.
Now, more importantly, why you wouldn't want to create a static method? Basically, polymorphism goes out of the window. You'll not be able to override the method, nor declare it in an interface (pre-Java 8). It takes a lot of flexibility out from your design. Also, if you need state, you'll end up with lots of concurrency bugs and/or bottlenecks if you are not careful.
回答4:
After reading Misko's articles I believe that static methods are bad from a testing point of view. You should have factories instead(maybe using a dependency injection tool like Guice).
how do I ensure that I only have one of something
only have one of something The problem of “how do I ensure that I only have one of something” is nicely sidestepped. You instantiate only a single ApplicationFactory in your main, and as a result, you only instantiate a single instance of all of your singletons.
The basic issue with static methods is they are procedural code
The basic issue with static methods is they are procedural code. I have no idea how to unit-test procedural code. Unit-testing assumes that I can instantiate a piece of my application in isolation. During the instantiation I wire the dependencies with mocks/friendlies which replace the real dependencies. With procedural programing there is nothing to "wire" since there are no objects, the code and data are separate.
回答5:
A static
method is one type of method which doesn't need any object to be initialized for it to be called. Have you noticed static
is used in the main
function in Java? Program execution begins from there without an object being created.
Consider the following example:
class Languages
{
public static void main(String[] args)
{
display();
}
static void display()
{
System.out.println("Java is my favorite programming language.");
}
}
回答6:
Static methods in java belong to the class (not an instance of it). They use no instance variables and will usually take input from the parameters, perform actions on it, then return some result. Instances methods are associated with objects and, as the name implies, can use instance variables.
回答7:
No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.
回答8:
If you apply static keyword with any method, it is known as static method.
- A static method belongs to the class rather than object of a class.
- A static method invoked without the need for creating an instance of a class.
- static method can access static data member and can change the value of it.
- A static method can be accessed just using the name of a class dot static name . . . example : Student9.change();
- If you want to use non-static fields of a class, you must use a non-static method.
//Program of changing the common property of all objects(static field).
class Student9{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student9(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student9.change();
Student9 s1 = new Student9 (111,"Indian");
Student9 s2 = new Student9 (222,"American");
Student9 s3 = new Student9 (333,"China");
s1.display();
s2.display();
s3.display();
} }
O/P: 111 Indian BBDIT 222 American BBDIT 333 China BBDIT
回答9:
Static methods are not associated with an instance, so they can not access any non-static fields in the class.
You would use a static method if the method does not use any fields (or only static fields) of a class.
If any non-static fields of a class are used you must use a non-static method.
回答10:
Static methods should be called on the Class, Instance methods should be called on the Instances of the Class. But what does that mean in reality? Here is a useful example:
A car class might have an instance method called Accelerate(). You can only Accelerate a car, if the car actually exists (has been constructed) and therefore this would be an instance method.
A car class might also have a count method called GetCarCount(). This would return the total number of cars created (or constructed). If no cars have been constructed, this method would return 0, but it should still be able to be called, and therefore it would have to be a static method.
回答11:
Actually, we use static properties and methods in a class, when we want to use some part of our program should exists there until our program is running. And we know that, to manipulate static properties, we need static methods as they are not a part of instance variable. And without static methods, to manipulate static properties is time consuming.
回答12:
Use a static method when you want to be able to access the method without an instance of the class.
回答13:
Static methods don't need to be invoked on the object and that is when you use it. Example: your Main() is a static and you don't create an object to call it.
回答14:
Static methods and variables are controlled version of 'Global' functions and variables in Java. In which methods can be accessed as classname.methodName()
or classInstanceName.methodName()
, i.e. static methods and variables can be accessed using class name as well as instances of the class.
Class can't be declared as static(because it makes no sense. if a class is declared public, it can be accessed from anywhere), inner classes can be declared static.
回答15:
Static:
Obj.someMethod
Use static
when you want to provide class level access to a method, i.e. where the method should be callable without an instance of the class.
回答16:
Static methods can be used if
One does not want to perform an action on an instance (utility methods)
As mentioned in few of above answers in this post, converting miles to kilometers, or calculating temperature from Fahrenheit to Celsius and vice-versa. With these examples using static method, it does not need to instantiate whole new object in heap memory. Consider below
1. new ABCClass(double farenheit).convertFarenheitToCelcium() 2. ABCClass.convertFarenheitToCelcium(double farenheit)
the former creates a new class footprint for every method invoke, Performance, Practical. Examples are Math and Apache-Commons library StringUtils class below:
Math.random() Math.sqrt(double) Math.min(int, int) StringUtils.isEmpty(String) StringUtils.isBlank(String)
One wants to use as a simple function. Inputs are explictly passed, and getting the result data as return value. Inheritence, object instanciation does not come into picture. Concise, Readable.
NOTE: Few folks argue against testability of static methods, but static methods can be tested too! With jMockit, one can mock static methods. Testability. Example below:
new MockUp<ClassName>() {
@Mock
public int doSomething(Input input1, Input input2){
return returnValue;
}
};
回答17:
Static methods are the methods in Java that can be called without creating an object of class. It is belong to the class.
We use static method when we no need to be invoked method using instance.
回答18:
I am wondering when to use static methods?
- A common use for
static
methods is to accessstatic
fields. But you can have
static
methods, without referencingstatic
variables. Helper methods without referringstatic
variable can be found in some java classes like java.lang.Mathpublic static int min(int a, int b) { return (a <= b) ? a : b; }
The other use case, I can think of these methods combined with
synchronized
method is implementation of class level locking in multi threaded environment.
Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I should use a static method?
If you need to access method on an instance object of the class, your method should should be non static.
Oracle documentation page provides more details.
Not all combinations of instance and class variables and methods are allowed:
- Instance methods can access instance variables and instance methods directly.
- Instance methods can access class variables and class methods directly.
- Class methods can access class variables and class methods directly.
- Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.
回答19:
A static method has two main purposes:
- For utility or helper methods that don't require any object state. Since there is no need to access instance variables, having static methods eliminates the need for the caller to instantiate the object just to call the method.
- For the state that is shared by all instances of the class, like a counter. All instance must share the same state. Methods that merely use that state should be static as well.
回答20:
In eclipse you can enable a warning which helps you detect potential static methods. (Above the highlighted line is another one I forgot to highlight)
回答21:
When static methods can be good?
There are only two situations when static methods or variables are being used and it's not an abomination.
- Declaring a true global constant, not a global variable. A global constant. Example: Math.PI. This is a fair shorthand for really saying that there is one instance of the universe, and that universe singleton contains a mathematical concept singleton in which there is a property PI which does not change. This concept seems strange to us because we are used to not thinking about PI in the context of object oriented responsibility. It would become more obvious if we were designing some strange game where there were alternate universes with different mathematical concepts and constants.
- Object creation. Static methods are a valuable and valid method of object creation. Overloaded constructors that take different arguments are not very clear and are often made clearer by replacing them with a static constructor.
When static methods are bad?
One way to think about static methods is as global procedures. Essentially a static method can be called anywhere from anywhere. It just pretends to be part of a class, when really the class is only used as a “tag”, which organizes the method by some logical division. I look at static methods in these terms, because creating global procedures is the exact opposite of object oriented design.
Another major problem with static methods is the testability. Testability is a big deal when building software. Static methods are notoriously difficult to test, especially when they create new instances of concrete classes. If you have ever worked in legacy code and tried to write a unit test for a static method, you know my pain.
Static methods also are not polymorphic. If you create a static method on a class, there is no overriding that behavior. You are stuck with a hard coded reference to that implementation.
Final words
So just remember when you create a static method to think about it carefully. I am not advocating never using them. I am advocating having a really good reason and checking first to see if the static method really belongs to another class where it can use state information.
来源:https://stackoverflow.com/questions/2671496/java-when-to-use-static-methods