• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Difference between Static and Instance Methods

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi all

There is always a confusion , to decide whether to keep a method static or not, i know that static methods don't pertain to a specific object,and U can call them, using Class name. But i want to get a practical aspect of difference.
Thanks in advance
 
Ranch Hand
Posts: 724
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,
look at Java classes. For example there is the Math class which has only static methods. The reason is clear I think.
Also Collections has only static methods. I think that static methods are something like global methods and you must use them very carefuly.
 
Ranch Hand
Posts: 1170
Hibernate Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Prefer instance methods. Make static methods when you must.
Really you should condiser the methods purpose and wether it makes logical sense to be a part of the instance or the class.

i think mostly static methods are used for instance management such as caching and factory schemes.
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Lets see whether I can answer this.

Public class A {
int i = 0; //instance variable
public static void method1() {
i += 1;
//this.i += 1; will give compile error as static method can never
//use "this" keyword
}
public void method() {
 
Caesar Dutta
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please ignore the previous. I pressed TAB and ENTER accidentaly.

----------------------------------------------------------------------------
Lets see whether I can answer this.

Public class A {
int i = 0; //instance variable
public static void method1() {
i += 1;
//this.i += 1; will give compile error as static method can never
//use "this" keyword
}
}

But the above will not compile as a non-static variable cannot be
referenced within a static method. So if I make all my variables static
see what happens.

Let there be a Class "C" having a static variable int X.

C c1 = new C();
c1.X = 10;
C c2 = new C();
c2.X = 20;
C c3 = new C();
c3.X = 30;

Now if i say System.out.println(c1.X) the output will be 30 not 10.
So static methods should be for Class type (application oriented) and
instance method should operate mostly on instance variable (object's state
oriented).

Hope this helps.

Caesar
 
Sheriff
Posts: 7023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Moving this to the OO, Patterns, UML and Refactoring forum, where conversations on such design issues are often held around these parts...
 
Ranch Hand
Posts: 379
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Static method means that the method logic is common for all instances of a particular class. This has two implications

1. You cannot maintain state (if you do, it should also be static)
2. It is not thread-safe (since it cuts across all instances in all threads)

Static is something similar to a global variable, but for that particular class. As with global variables, you should not use it unless you are sure that the behavior is same across all instances.

A static getInstance() method is also used in the Factory/Singleton patterns.

For example,

A utility method like

boolean isStringValid(String id) {
/* logic not commonly found in String class or something specific to implementation */
}

or

String cleanString(String string) {
/* some cleaning logic */
}

can be a static method.

On the other hand,

String getName() {
/* Gets an instance variable */
}

or

void updateObjectState() {
/* Changes the state of the associated object by changing its attribute values */
}

cannot be static.
 
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I like static methods as syntactic shortcuts.


The risk with statics is you lose the ability to extend Logger and override the methods, or plug in a different logger that implements the old interface in a new way.

Of course we can work around anything. The static logger might say ...
 
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
If you don't like the typing, then just make an instance variable and referance it, it won't be so hard to change later on.

It's easy to build a class that should exist as an instance as a static class, but just because it's easy to accomplish doesn't mean it's a good idea - in fact, its usually the opposite.

I believe proper OO shouldn't use static (global!) anythings at all, except constructors.

What that means is that any object can create any other available object for its personal use, or to give away. But it can't access global methods grouped conviniently under a class name. You dont have verbs without a noun to do them, do you?
 
Stan James
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"Proper OO" is something we could debate forever so I won't try to argue just how proper static methods might be. Classes with all static methods and no data are common practice, often stereotyped as "utility" classes. My example of simplified syntax is probably an isufficient reason to make one, but for my personal projects a single static logger has worked fine for years. On the other hand, I've been hurt while using a commercial framework by the problems I mentioned above - static helpers are hard to extend, override or replace.
 
Maxim Katcharov
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Now that's not very nice, you cant expect to say "debating this is a bad idea, so we won't continue. In closing, here is my view:" and then not have the other respond.

What I understood from your first post was that you think static methods make things easier. You like static methods as syntactic shortcuts. I don't. In fact, I'm very opposed. Instead of changing the design of a class for the sake of 10 keystrokes * 20, why not just copy-paste them? And "Logger log = [really long method calls]; log.whatever();" can likley do the trick in case things aren't clear inside the methods.

You state that they're hard to replace, and offer the solution of "public static void log(String message)". I don't think that that's different from using a static as an instance, except now you're forcing an instance to act as that static. If two different sections of your project later need to use a logger (different instances of), you'll end up with either a very useless static to clean up, or, likley, something horrible like an added "...void log2(String...".
 
Stan James
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Sorry, didn't meant to shut down your point of view, just to say that we're likely to disagree no matter how much we write, and disagreeing is ok.

"how OO" something is really matters little. Nobody has a good metric, except Alan Kay: "OO == Smalltalk" How you can live with a design over time does matter. Statics are probably a compromise. Some compromises are fine so long as they don't turn around and bite you. A guideline like "no statics" is good if it only makes you stop and think about he compromise when you use them. It sounds as if you have decided to never accept the risks that come with them and I have a different comfort level. Happens all the time.
 
Stan James
(instanceof Sidekick)
Posts: 8791
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Seprate note for a slightly different take on the topic ...


If two different sections of your project later need to use a logger (different instances of)



I often use the logger example for statics, and this response often comes up. I've never had a need for different loggers yet. Anybody else?

My current project uses a vendor package with a single static LogHelper. It is configured with message filters and log writers. I configured two filters with different writers - one provided writer writes to stdout and the other that I wrote writes to an in-memory method-level performance monitoring table.
 
Maxim Katcharov
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Statics are probably a compromise. Some compromises are fine so long as they don't turn around and bite you.



I definitley agree with that. Makes no sense to do something 'right' if you know doing it will be wrong for the current situation.

Good point on not having to create two loggers, can't say much against that. I wouldn't like to make a static logger myself though, even if I did know that I would never need a second. Just seems odd to me, I'd prefer the typing, or a change in design. Like you said, we're comfortable with different things.
 
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'd remove "static" from methods and make every method implicitly static as long as it does not use any class member attributes (variables). Compiler would take care of that. To remove human error.
 
Vladas Razas
Ranch Hand
Posts: 385
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ha. Was too fast with my answer. I forgot that static marked methods are not polymorphic. Sorry. My suggestion wouldn't work. Though if static methods would be polymorphic at least singletons could be subclassed no problem.
 
Ranch Hand
Posts: 127
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Hi,
suppose one instance is executing this method and suppose it is in a for loop constructing a temporary clean string. At the same time another instance calls MyClass.cleanString("anotherstring").
As static is not thread safe, first requester may be returned an unexpected wrong result.
Am I wrong?
Thanks..
Murat
 
Ranch Hand
Posts: 995
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Murat I suppose that the method you described is static?

However the method is thread safe if the thread safeness conditions are met: what I mean: if the computation in the method does not use class/object variables it is thread safe as local variables are thread safe. In the case the computation uses class/object variables, indeed the result may be unexpected as one/more values of the class/object variables might be modified by a concurrent thread.

./pope
 
Ranch Hand
Posts: 872
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
90% of my applications usually comprises of Utility Class methods. I love them because they are easier to reuse then any inheritance or object composition. Even if I am converted back to object oriented programming methodology from Procedural, I will never give up the use of good old Class methods.
 
Alexandru Popescu
Ranch Hand
Posts: 995
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Agree with you Gerald. In an app there will be almost always a need for some statics.

./pope
 
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I find that I use static methods almost by default when I need a utility type method. Often, I find that I can refactor several it into an object. Lately, I've been trying to focus on not writing so much static stuff. In addition to being harder to test, it is potential harder to reuse (because you can't subclass.)
 
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I also use static methods on utility classes, but often only because I can't put the methods on the class they really belong to (as I can't change that one). For example, it would be much better if most of the methods in my StringUtilities class actually where instance methods of the String class itself.

Similar with java.lang.Math - it actually only exists because primitives aren't objects. In more OO languages you could write 42.sin() instead.
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Gerald Davis:
90% of my applications usually comprises of Utility Class methods. I love them because they are easier to reuse then any inheritance or object composition.



You keep saying that - and I still don't buy it.
 
Gerald Davis
Ranch Hand
Posts: 872
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I said that before , o gosh I am so forgetful. I get that problem ,I forget what it is called , when you forget what happend in the past completely.

What mean by this message is ,my programming style is Procedural but because I have a good understanding of OOP and good programming practice, I create code that is easy to understand and modify ,that what I like to believe anyway.

I love using Object Oriented Librarys in my application, using Object Oriented Librarys is much easier then implementing OOP in an application.
 
Alexandru Popescu
Ranch Hand
Posts: 995
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ilja I wouldn't go too for that 90%, but I can guarantee you that in any piece of app there is something static (at least we can count the main ).

./pope
 
Ilja Preuss
author
Posts: 14112
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Originally posted by Ali Pope:
Ilja I wouldn't go too for that 90%, but I can guarantee you that in any piece of app there is something static (at least we can count the main ).



Yes, of course - I didn't mean to imply that static methods should be avoided totally. I like to use them as creation methods, for example.

They are easy to misuse, though. Whenever I see a static method, i look out for the Feature Envy smell, and often enough I find something that tells me the code wants to be moved to a real object...
 
Ranch Hand
Posts: 502
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I would use a static method as a shortcut for things like Logger, as long as the static method wraps the call to the real object. So, for example, I would have something like this



So, the log function provides a shortcut method and the RealLogger provides extensibility
 
Jeanne Boyarsky
author & internet detective
Posts: 41860
908
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Jayesh,
For something simple, like logging, this makes sense. However if the real object does something more complex (like call the database), embedding static calls in the app makes it harder to change later.
 
reply
    Bookmark Topic Watch Topic
  • New Topic