Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why do we use static methods?

 
krishna balaji
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i understood concept of static variables
can any one explain concept of static methods ?
why do we use static methods?
what all situations in which we can use static methods ?
why main is static?
where should we must use static and where satic methods should not be used?


Thanks
 
David McCombs
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static methods are conceptually the same as static variables, thus the reasons to use or not use them are similar. They belong to the class, not specific objects of that class. An example from the java API is Math, all the variables are static. Does it make sense to have to create a Math object just to call a single method? Other then the fact that the methods perform some mathematical operation, there is little relation between them. In other words, there are no logical instance variables that would tie the math methods together. As an aside, you can't instantiate Math, so don't waste time trying.

A simple answer to why and when is 'whenever it makes sense". If a method needs to be in a class, but not tied to an object, then it makes sense. If the method is more logically part of an object, then it shouldn't be

Main is static because someone at Sun decided it would be better if the JVM could call main without creating an object first. It probably simplified the design of the JVM.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
where should we must use static and where static methods should not be used?


They are never really necessary. You could always do new Math().method() instead of Math.method().

There are some disadvantages. When you call one, you couple yourself directly to the class. It's impossible to use polymorphism and swap in another class later.

I've used them as a lazy shortcut (to avoid having to instantiate and object) and come to regret it several times. I stop and think hard before I add new static methods and especially classes with all static methods.
 
David McCombs
Ranch Hand
Posts: 212
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Stan James:


They are never really necessary. You could always do new Math().method() instead of Math.method().

There are some disadvantages. When you call one, you couple yourself directly to the class. It's impossible to use polymorphism and swap in another class later.

I've used them as a lazy shortcut (to avoid having to instantiate and object) and come to regret it several times. I stop and think hard before I add new static methods and especially classes with all static methods.


You can instantiate Math?
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by David McCombs:
... You can instantiate Math?

Correct me if I'm wrong, but I think that was a hypothetical example -- just to illustrate that static methods in Math could work much the same way if they weren't static and if Math could be instantiated.
 
Red Smith
Ranch Hand
Posts: 136
1
Netscape Opera Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by krishna balaji:
i understood concept of static variables
can any one explain concept of static methods ?
why do we use static methods?
what all situations in which we can use static methods ?
why main is static?
where should we must use static and where satic methods should not be used?


Thanks


One use is when you want process data in a non-object-oriented way using what would be called "functions" in C and other languages. In addition to the Math class mentioned, there is the Arrays class (and probably others) that are just sets of C-style functions.
 
Shrikanth Nekkanti
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi krishna balaji

Let me clear your doubts
1.why do we use static methods?

To use a particular method in Java we first create a object to class which that method belongs to.Then by using object name.method name we call that method.

Example:
class Demo1
{
static dummyMethod1()
{
----------
-------
}
}

class Sample
{
public static void main()
{

//Use demo class method using classname.methodname
Demo1.dummyMethod1();

2.what all situations in which we can use static methods ?

The advantage of static method is we can use that method using classname.methodname without creating object to class to which it belongs.

Example:
class Demo
{
int dummyMethod()
{
----------
-------
}
}

class Sample
{
public static void main()
{
//create object to demo class
Demo obj=new Demo();

//Use demo class method using object
obj.dummyMethod();

3.why main is static?

To call a method in java we need an object.Program execution starts from main method we dont have a object to call main method in the begining.When JVM sees main method in program it starts execution from there.Since main method is static we can execute it without creating an object.


4.where should we must use static and where satic methods should not be used?

NOW YOU can answer this question i guess.
 
Red Smith
Ranch Hand
Posts: 136
1
Netscape Opera Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops, replied to my post when I was trying to edit it....
[ August 09, 2007: Message edited by: Red Smith ]
 
Gavin Tranter
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dont you need static methods, when you wish to create objects using the Singleton pattern?
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oops, yes, Math was a bad example. Make that BistroMath.

I think there's going to be something static - methods or variables - to get the "global" access to a singleton. Would some other kind of registry work ... JNDI?
 
Red Smith
Ranch Hand
Posts: 136
1
Netscape Opera Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Gavin Tranter:
Dont you need static methods, when you wish to create objects using the Singleton pattern?


I found an example of a Singleton pattern in Java and they do make the constructor private to prevent normal instantiation and use a static to create one instance of the object:



http://www.javacoffeebreak.com/articles/designpatterns/index.html
 
Pat Farrell
Rancher
Posts: 4678
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The above Singleton patter is not thread safe.
Singletons are frequently overused, but that is a topic past a beginner's level.
 
tanuj pangtey
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
to save space in heap we use static, 'cause if you are not instantiating any class then it wouldn't make object in heap............
 
Campbell Ritchie
Sheriff
Pie
Posts: 50196
79
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Tanuj Pangtey, welcome to the Ranch.

I am not at all convinced about saving space in the heap. And people will by now have realised that it is impossible to instantiate the Math class!

I think there are two justifications for using static methods.

1: You do not have access to an instance of the class Examples
  • The main method has to be invoked before any objects are created at all.
  • The Singleton or similar getInstance() methods, even though the Singleton example given only works in a non-threaded application.
  • A method for retrieving an instance which has been serialised.

  • 2: When you neither use nor alter any of the object's state.
    You can have a method which takes parameters

    Caller--->information---->Method

    You can have a method without parameters

    Caller--->nothing-------->Method

    You can have a method with a return type

    Caller<----information<---Method

    You can have a method with a void return type

    Caller<---nothing<--------Method

    This is what all beginners are familiar with, but the method works the other way too

    Method--->information---->object state.

    That means it may alter the method state (changing the value of any fields)

    Method--->nothing-------->Object state.

    This method doesn't change any of the fields.

    Method<---information<----Object state.

    This method uses information from the fields in its workings.

    Method<---nothing<--------Object state

    This method doesn't use any information from any of the fields in its workings.

    Put them together

    Method<---nothing<--------Object state
    --->nothing-------->Object state.

    We now have a method which doesn't use the object state at all. Example:-
    Math.sin(). It takes a parameter, and calculates a result. But it doesn't need any access to any fields.
    Another example:-This takes all its information from the parameter, uses a formula and returns the answer. It doesn't do anything with the fields of the instance.

    So, any method which does not take any information from a field, and does not put any information into a field, does not have to be an instance method. Any method which does not use or alter any fields in its class or object might as well be a static method.
     
    Roger Chung-Wee
    Ranch Hand
    Posts: 1683
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Another thing to consider is that you cannot override a static method because it is implicitly final. This makes JUnit testing difficult, so I would only use a static method which performs some small utility function and which I won't be JUnit testing.
     
    Rob Spoor
    Sheriff
    Pie
    Posts: 20665
    65
    Chrome Eclipse IDE Java Windows
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Originally posted by Roger Chung-Wee:
    Another thing to consider is that you cannot override a static method because it is implicitly final.

    Not quite.

    You can "override" a non-final static method, although this is actually redefining it and hiding the original method; similar to redefining fields.
    If you mark a static method as final however, no subclass can define a static method with the same signature.
     
    Raghavan Muthu
    Ranch Hand
    Posts: 3381
    Mac MySQL Database Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Originally posted by Roger Chung-Wee:
    ....This makes JUnit testing difficult, so I would only use a static method which performs some small utility function and which I won't be JUnit testing.


    Isn't it way too much for a beginner's level and out of context as such?
     
    Raghavan Muthu
    Ranch Hand
    Posts: 3381
    Mac MySQL Database Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Krishna Balaji,

    As Campbell has clearly explained, i guess it would help you though. Just to summarise, if at all you want your method to make use of any of the instance values to perform its operation they should be instance level methods.

    On the other hand, if your method does NOT depend on any of the instances (and of course instances means values of instances), they can better be static methods. One advantage you get with the static methods is you don't need an object to call a static method, thereby you could save an object's memory there.

    In case of Math class, the way it is being fully static, there is absolutely no necessary to create/have an instance of it. Hope CR's explanation would better help you to get clarified with this.

    Math class serves the purpose of being a general purpose utility class which does NOT depend on any specific instance and its state
     
    • Post Reply
    • Bookmark Topic Watch Topic
    • New Topic