As a general convention, should static method(s) be separated into another class from a class with instance methods?
Is there also an example of your reason?
There is no general convention that dictates that a static method must be separate from a non-static method. In fact, if the two methods are related enough to one another, it would be counter-intuitive to have the methods separated.
Recall what use case static methods (and fields) have: they're methods/fields that can be used without an instance of a particular class. This generally means that they hold valuable metadata or perform a useful operation that's related to their class instance, but would not require direct instantiation of that class.
Take, for example, Integer. It has the static [final] fields MAX_VALUE and MIN_VALUE. Since both of these fields contain fixed information that would not change between instantiations, it would not make sense to have to instantiate an Integer to get this information.
Integer also has the useful operation parseInt, which takes a String and turns it into an int. We shouldn't require an instance of Integer to convert from String to int, especially if we're not placing it into an instance of Integer.
The overarching convention has been to keep related methods together, regardless of if they're static or not. You can see clearer examples of this in certain Java library classes, like Integer.
It probably is a duplicate question, but no, static methods have very specific benefits that are often valuable in classes that are instantiated as objects.
There is no such convention. It's completely depends on your situation. Some class may really needs mixture of both static and non-static members.
But some times it's is seen the use of Constatns.java/ Utils.java class in some java project. You may found -
public static final double PI = 3.1416;
public static getArea(double r){}
This class contains some final static property and some final method. The purpose of these class to provide some constants or utility method all over the project.
Definitely answer would be dictated by the use case but there is no convention as such. At most you have some Utility class that may have bunch of static methods that are used by other classes as helper methods. For example to test whether a String is an email or to extract username from email etc.
Putting all static methods in a separate class would be useful while writing an API or a framework. Collections class is an example. java.lang.Math or java.lang.System is another.
Normally, define static methods in the following scenarios:
While writing utility classes .
If the method does not use any instance variable.
If any operation is in-dependent of instance creation.
If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
see here - https://stackoverflow.com/a/5313383/760393
Related
We use System.out.println without instantiating it or creating object of it. Same goes to Math class and many others (I guess). Is there something special about these classes? Can we use the classes and methods declared within those classes in same fashion? Please help.
You don't have to create objects for the System and Math classes because the methods and variables in those classes are static. This means that they belong to the class itself, not to instances of the class.
For reference see:
Understanding Class Members
Beyond Basic Arithmetic
This is something called 'static' method. In order to invoke static method, you do not need to have an instance of the class.
This also has other side effects such as non-existing 'this' and thus static methods cannot invoke instance methods.
This is mostly used for some sort of utility classes which are often stateless.
Math is a good example for it.
I suggest to read a bit about static methods and static in Java in general.
You don’t need to create object of System and Math class to use it because they have static methods. Static methods belong to the class and thus doesn’t require it to be instantiated.
Although, you can create its object and then also use those methods, but creating a class for static method is of no use.
Why don't we have to create object of System or Math classes in java and use them directly?
Because the methods of Math are declared as static methods, and because System.in / System.out / System.err are static variables.
Is there something special about these classes?
No. Any variables or methods that are declared as static will behave that way.
Can we use the classes and methods declared within those classes in same fashion?
I don't really understand what you are asking there. But, if you are asking if you can create an instance of Math or System so that you can do something like this:
Math myMath = new Math();
myMath.min(1, 2);
No, you can't. Neither of those classes has a public constructor, so you can't new them.
And if you could do that, it would be really bad style!
Reference:
Understanding Class Members
First,you cannot make an instance of the class Math,because it has only a single constructor and it's been marked private and you just can't make an instance of it from outside the class.
Snapshot of the source code of the class Math
Second,you don't need to do that.All of the methods in class Math are static,just use the class name and the dot operator and you can invoke any one of them.
System class can't instantiate/create object because this System class have private constructor.
And it's all members and methods are static, that can be accessible directly by Class name.
this simple and valid answer will help you.
We don't instantiate every other class or method because the JVM(Java Virtual Machine) already loads them into the project and hence, we can use these classes again and again. One such example is the main method. These classes/methods are already predefined for us so there is no need for us to instantiate such classes/methods because they are static.
You don't have to instantiate the object in order to use methods of the math class.
Because to use this methods we don't need object. We can directly invoke this.
These type of classes are called static. Here methods can directly invoked by the class itself.
They are already defined in the JVM. We don't need to instantiate to use methods of this class.
I am looking at other peoples' code.
I see a class with no non-static fields but in which most of the methods are non-static, requiring you to make an object to access methods that effectively operate statically.
Is there a possible reason for this, that I am just not understanding?
EDIT
Someone asked for examples. Here is some more info.
For instance there is a file manager class. The only fields are static and are Comparators. There are some methods to do things like sort files in a list, count files, copy files, move files to an archive folder, delete files older than a certain time, or create files (basically take a base name as string, and return a File with given base name and date/time tacked on the end.)
9 non-static methods
5 static methods
I don't see a particular rhyme reason for the ones that are static vs non.
One particularly odd thing is that there are two methods for removing files. One that removes a file no matter what, and one that only removes it if it is empty. The former is a static method while the latter is not. They contain the same exact code except the later first checks if the file.length is 0.
Another odd one is a class that does encryption - all fields and methods are static but it has a constructor that does nothing. And an init() method that checks if a static variable contains an object of itself and if not instantiates an object of itself into that field that is then never actually used. (It seems this is done with a lot of classes - init methods that check for an object of itself in a static variable and if not instantiate itself)
private static File keyfile;
private static String KEYFILE = "enc.key";
private static Scrambler sc;
It has methods to encrypt and decrypt and some methods for dealing with key and file.
Does this make sense to anyone? Am I just not understanding the purpose for this stuff? Or does it seem weird?
Objects don't have to have state. It's a legitimate use case to create an instance of a class with only behaviour.
Why bother to create an instance ? So you can create one and pass it around e.g. imagine some form of calculator which adheres to a particular interface but each instance performs a calculation differently. Different implements of the interface would perform calculations differently.
I quite often create classes with non-static methods and no members. It allows me to encapsulate behaviour, and I can often add members later as the implementation may demand in the future (including non-functionality related stuff such as instrumentation) I don't normally make these methods static since that restricts my future flexibility.
You can certainly do it that way. You should look carefully at what the instance methods are doing. It's perfectly okay if they're all operating only on parameters passed in and static final static class constants.
If that's the case, it's possible to make all those methods static. That's just a choice. I don't know how the original developers would justify either one. Maybe you should ask them.
Let me rephrase this question a bit,
Even though methods are non-static why would one declare fields as static?
I have taken below quoting from Java Docs,
Sometimes, you want to have variables that are common to all objects. This is
accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole.
For Bicycle example, kindly refer the Java Docs.
Making all methods non-static allows you to override them. This makes it a lot easier to use this class in testing, because instead of the actual implementation you can use a mock that behaves as you want it for the tests. Static methods are, in my book, a code smell and should be avoided unless there's a good reason (e.g. quite trivial utility methods).
Also, at some point in the future you might want to change the behaviour of the methods in some situation, e.g. in the form of a strategy.
In the case of your encryption class, you might want to hand your class an instance of the encryption class to handle encrypting/decrypting, but be able to configure the details in some other place. That would allow you to change the algorithm and much more easily test your own code without also having to test the encryption.
The wrapper class Integer has the static method parseInt() which is used like this:
Integer.parseInt();
I thought only methods of static classes could be called like this (i.e. Class.doMethod()). All non-static classes need objects to be instantiated to use their methods.
I checked the API, and apparently Integer is declared as public final Integer - not static.
Any class can contain both static and non-static methods. When calling the static methods on any class - including your own - you don't need to instantiate an instance of the class, just call the method using the class name: MyClass.methodName().
In fact, even the following will work:
Integer nullInt = null;
nullInt.parseInt("5");
This works because only the class type of the reference is important when calling static methods. But consider this poor style: always use e.g. Integer.parseInt instead.
Also note that you can't declare a top-level class as static anyway: only nested/inner classes can be declared as static.
No, you are wrong.
Only static methods can be called like this, but they may belong to 'non static' classes.
In java, static methods may be called from objects, but this only generates a warning and still compiles.
A non-static class can have static fields and methods that are shared by all instances (this is why "Shared" means static in VB.NET). Therefore accessing a static member from an object can confuse the reader, and must be avoided.
A way to phrase it: An Integer is a concrete object; you can have many Integers. There is only one Integer.MAX_VALUE.
That's to say, there are some things with Integers that are concrete, and others that only need to exist once, anywhere.
I know the difference between static type and other types but I am not sure which is to used where. Now I am using static types in all places to avoid object instantiation. Is it a good idea to use it that way ? Is there any particular disadvantage in using static type in all places ??
EDIT
What do you call this as static String staff ?
This is an excellent question. Usually you should not use static methods/variables unless you know for sure that it's a correct application for it. In object oriented programming (OOP), objects encapsulate data and behavior. Typically, *instance methods are used to manipulate the object's data.
Static methods/variables should only be used for functionality that is not associated with any particular object. A good example of a valid application for static is Math.random().
Some notes about instance and static methods/variables:
Instance variables have access to static and instance variables/methods, but static methods can only access other static variables/methods.
A static variable will always be the same across all instances of a class.
A good book to read that covers this topic is Clean Code by Robert Martin. Highly recommended.
*instance methods are the opposite of static methods. They are associated with a class instance, instead of the class itself.
Addressing your edit, assuming that that's a variable, you'd access it like this:
MyClass.staff = "bob, george, and linda";
System.out.println(MyClass.staff);
Edit: here's a post I made on another forum a while back, with some good answers. It's a PHP forum, but the concepts still apply.
http://forums.devnetwork.net/viewtopic.php?f=1&t=127667
When there are multiple instances of an object, static-typed variables and functions are shared across all instances.
Most logic in any application will be modularized, and will operate on some shared fields. This is the reason why most methods are non-static. The 'fields' in this case can be something as basic as 'firstName', etc. But in other cases, the 'fields' are instances of other classes such as DataAccess (DAO) classes.
Variables i.e. fields should almost never be static, unless they are 'constants'.
A good example where you will be use static methods is a class that transforms Strings, for example:
public class StringUtil{
public static String convertToHex(String orig){
}
}
This question already has answers here:
Should private helper methods be static if they can be static
(20 answers)
Closed 9 years ago.
What do you think about using private static methods?
Personally, I prefer using a static private method to non-static as long as it does not require access to any instance fields.
But I heard that this practice violates OOP principles.
Edit: I am wondering from style prospective of view, not performance.
A private static method by itself does not violate OOP per se, but when you have a lot of these methods on a class that don't need (and cannot*) access instance fields, you are not programming in an OO way, because "object" implies state + operations on that state defined together. Why are you putting these methods on that class, if they don't need any state?
(*) = In principle, due to the class level visibility in Java, a static method on a class has access to instance fields of an object of that class, for example:
class Test
{
int field = 123;
private static void accessInstance(Test test)
{
System.out.println(test.field);
}
}
You need to pass in the reference to an instance (this pointer) yourself of course, but then you are essentially mimicking instance methods. Just mentioning this for completeness.
As mentioned above, private static methods are often useful for organizing re-used logic and reducing/eliminating repeated code. I'm surprised that I haven't noticed any mention of performance in this discussion. From Renaud Waldura's 'The Final Word on Final':
(Note, private static methods are implicitly final)
"Since a final method is only implemented in the declaring class, there is no need to dynamically dispatch a call to a final method, and static invocation can be used instead. The compiler can emit a direct call to the method, bypassing entirely the usual virtual method invocation procedure. Because of this, final methods are also candidates for inlining by a Just-In-Time compiler or a similar optimization tool. (Remember, private/static methods are already final, therefore always considered for this optimization.)"
Check out the whole paper: http://renaud.waldura.com/doc/java/final-keyword.shtml
private or public doesn't make a difference - static methods are OK, but if you find you're using them all the time (and of course instance methods that don't access any instance fields are basically static methods for this purpose), then you probably need to rethink the design. It's not always possible, but most of the time methods should reside with the data they operate on - that's the basic idea of OOP.
I don't necessarily see any real problem with what you are doing, but my first question would be if the method doesn't require access to any instance fields, then what is it doing in that class in the first place?
It's a matter of taste, but I make methods that don't react to a state within the object static. This way I don't have to rewrite code if a static function needs similar functionality. A sorting function would be a good example of such a case.
I tend not to use private static methods. I do use public static methods and group them into Util classes to promote reuse.
Private static methods can for example operate on private static members of their class. This can be utilized to encapsulate and unify certain class specific operations.
The major drawback of using static methods is in my opinion the fact that one throws away the possibility to override. Since classes in Java are not like, let's say, classes in Smalltalk, you can not override static methods.
Since your question relates to private static methods, overriding is out of option anyway.
I tend to use static methods only in case of utility classes (like java.lang.Math) or patterns like the Singleton pattern. All of these require a higher visibility than private, because they represent services provided by their class to others.
Final thought: If you have one or more private static methods, think about extracting them to a dedicated utility class and making them public. Even better, make them instance methods and use the Singleton pattern.