Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

I'm still confused about when to use Static  RSS feed

 
Naziru Gelajo
Ranch Hand
Posts: 175
1
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was hoping that folks here could give me a better idea on when to use static for variables and methods and when not to use static for variables and methods. I shouldn't use static if I'm returning a value correct? Thanks in advance!
 
Peter Muster
Ranch Hand
Posts: 74
5
Eclipse IDE Python Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Naziru Gelajo wrote:I was hoping that folks here could give me a better idea on when to use static for variables and methods and when not to use static for variables and methods. I shouldn't use static if I'm returning a value correct? Thanks in advance!

I wouldn't say that.

I use static for variables when they should be available for the whole class, constants are a good example, or Loggers. I use static for methods when I either want to control instantiiation, like for a Singleton, or the method is purely algorithmic, meaning I don't need to take object states or class / instance members into account for the calculation.

One way to learn when to use static is to observe classes that are part of the Java Runtime, especially the ones you have already used and a familiar with. Check for instance Calendar or File in the Oracle documentation and pay attention for which methods and fields the static modifier is used.
 
Paul Clapham
Sheriff
Posts: 22471
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nothing wrong with a static method which returns a value. Consider the Math.sqrt() method for example: it returns a value, namely the square root of its parameter. It's like Christian said, purely algorithmic and it doesn't use or affect the state of any object in the Math class.

Or consider the Thread.sleep() method, which causes the current thread to sleep for a specified time. It's a static method because you can only cause the current thread to sleep. Causing other threads to sleep isn't allowed by the API, so there's no need for an instance method named sleep() which could be used to cause some other thread to sleep. You'll find several methods like this in the Thread class, with the common feature that they can only apply to the current thread.
 
Naziru Gelajo
Ranch Hand
Posts: 175
1
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok guys thanks, can either of you gentleman kindly provide an example of when one will make a method static and a time when someone won't make a method static? Thanks!
 
Shubham Semwal
Ranch Hand
Posts: 176
3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Naziru Gelajo wrote:I shouldn't use static if I'm returning a value correct?

Nope. I don't think static has much to do with returning values.
There are 2 parts to using the keyword :

1: Using static with variables -
Instance variables are one per Object i.e each object has it's own variable.
Whereas marking a variable as static means that there will be only 1 copy of the variable and all the objects will share the same variable.

Here's an example -
We all have our own toothbrushes. But at home we all share only 1 dining table. If someday mother decides to buy a new one then it'll be changed for all of us.
Toothbrush = one per person.(instance variable)
Dining table = one per house.(static variable)



Also since static variable are one per class we can access them using classname still the results will be same.


Where will you use it ?
We'll use it in situations where a piece of information is to be shared by all the objects of a class e.g - in counter variables, institution names, in constants(used with final) etc.

NOTE - static can not be used with local variables but final can be used.

2: Using static with methods -
Following are the properties of static methods.
  • It belongs to the class.
    Static methods are class methods.Just like static variables they can be accessed by using ClassName.methodName().
  • It can be invoked without object.
    Perhaps the greatest usability of static method lies in the fact that they can be called even before object creation. (Think : Why main() is static ?)
  • Can access and manipulate static data member.
    Non-Static data members can be accessed from static fields(methods) only with the help of objects. There is no such restriction for static methods accessing static data members.


  • Note - Although static methods can be inherited by by subclass they can't be overridden(strictly speaking).
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 7797
    142
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Shubham Semwal wrote:Where will you use it ?
    We'll use it in situations where a piece of information is to be shared by all the objects of a class e.g - in counter variables, institution names, in constants(used with final) etc.

    I only agree with constants. Counters and other mutable state should *NEVER* be globally accessible. Your example should actually look like this:




    Static variables should be used when something is truly constant, or maybe for cross-cutting concerns such as loggers.

    For all other cases, use dependency injection (like I demonstrated above by putting a Family's dependency on a Table in its constructor).
     
    Campbell Ritchie
    Marshal
    Posts: 55672
    161
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Shubham Semwal wrote:[. . .
    Here's an example -
    We all have our own toothbrushes. But at home we all share only 1 dining table. If someday mother decides to buy a new one then it'll be changed for all of us.
    Toothbrush = one per person.(instance variable)
    Dining table = one per house.(static variable)



    Also since static variable are one per class we can access them using classname still the results will be same.
    . . .
    I think that is a bad example and tables should not be static fields. What you are confusing is whom the table belongs to. Each person has a toothrbush, so toothbrush should be an instance field in the Person class. Different families have different tables so table should be an instance field in the Family class. Why are you having families called sister; a family might be called ritchie or semwal.
    Agree with Stephan. Don't make variables static and the only fields which can be non‑private are constants.

    Static members of a class should always be accessed by ClassName.memberName. Never use objectName.staticMemberName.
     
    Campbell Ritchie
    Marshal
    Posts: 55672
    161
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Christian Pflugradt wrote:[. . . One way to learn when to use static is to observe classes that are part of the Java Runtime, especially the ones you have already used and a familiar with. Check for instance Calendar or File in the Oracle documentation and pay attention for which methods and fields the static modifier is used.
    It is bad to try to learn from other people's ode without learning the principles first. Particularly from classes like Calendar which is a legacy class which you should no longer use.

    Simple answer. Never make anything static without good reason. If you are tempted to make things static because they are used from the main method and the code won't compile otherwise, you have written the main method wrongly. Constants should be static fields, because you only need one copy. As for static methods, that depends what data they access. Look at the most dubious classification of methods ever seen. If you can honestly say that your method is a 1368, then it can probably be made static.

    I see that Stephan has already shown you about the mistake about the Family class.
     
    Winston Gutkowski
    Bartender
    Posts: 10573
    65
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Naziru Gelajo wrote:I was hoping that folks here could give me a better idea on when to use static for variables and methods and when not to use static for variables and methods.

    I think others have provided you with detail, but my major piece of advice would be: DON'T. ... At least, not yet.

    Beginners almost always put static on far too many things, and the main reason is that you're often writing classes with a main() method in it.

    So my advice - at least while you're in the early stages - is: Try to make main() the only static method you write.

    And you might find this page worth reading for some tips on how to do that.

    HIH

    Winston
     
    Shubham Semwal
    Ranch Hand
    Posts: 176
    3
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Stephan van Hulst wrote:
    I only agree with constants. Static variables should be used when something is truly constant, or maybe for cross-cutting concerns such as loggers.

    I tried to make the code as simple as possible so didn't used so many classes as in the other example.

    What about the counter variables that keeps a track of how many time a program has run. Shouldn't that be static ? I don't know of any other way.
     
    Shubham Semwal
    Ranch Hand
    Posts: 176
    3
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Campbell Ritchie wrote: Don't make variables static and the only fields which can be non‑private are constants.

    I'm just trying to learn java concepts and I must confess that I never use access modifiers in my variable name. But thanks for pointing out I'll start using them from now on. It's a good practice.
     
    Campbell Ritchie
    Marshal
    Posts: 55672
    161
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Shubham Semwal wrote:. . . I never use access modifiers in my variable name. . . .
    Where are you learning? One of the first things you should learn is to make your fields private.
     
    Winston Gutkowski
    Bartender
    Posts: 10573
    65
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Shubham Semwal wrote:What about the counter variables that keeps a track of how many time a program has run. Shouldn't that be static ? I don't know of any other way.

    There isn't, since unless you intend to save the count somewhere at the start or end of execution, it will be lost as soon as the JVM exits. And if you're going to do that, why not create an ExecutionCounter class?

    IMO, the phrase "static variable" should be taught as anathema in Java courses, and I'll give my daily quota of cows to the first person who can give me a case for their use, in Java, that is legitimate, clear, and optimal.

    Winston
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 7797
    142
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Winston Gutkowski wrote:IMO, the phrase "static variable" should be taught as anathema in Java courses, and I'll give my daily quota of cows to the first person who can give me a case for their use, in Java, that is legitimate, clear, and optimal.


    I'll bite :P

    Like I said before, static variables can be used for cross-cutting concerns that are *really* class-based, such as declaring loggers. Now, if I were to design my own language, I would include a "log" keyword or somesuch, but you did ask about Java.

    This of course has little to do with core business logic, but I think it's legitimate, clear and optimal.
     
    Dave Tolls
    Rancher
    Posts: 2909
    35
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Stephan van Hulst wrote:
    Like I said before, static variables can be used for cross-cutting concerns that are *really* class-based, such as declaring loggers.


    You mean you don't declare your Logger as final?
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 7797
    142
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    I do, but that doesn't make it constant. That just makes the reference constant.
     
    Dave Tolls
    Rancher
    Posts: 2909
    35
    • Likes 1
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Stephan van Hulst wrote:I do, but that doesn't make it constant. That just makes the reference constant.


    It means it's not a variable.
    Which is what I think Winston is referring to.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 7797
    142
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Ah, you're correct.
     
    Winston Gutkowski
    Bartender
    Posts: 10573
    65
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Dave Tolls wrote:It means it's not a variable.
    Which is what I think Winston is referring to.

    Well spotted that man.

    Winston
     
    Shubham Semwal
    Ranch Hand
    Posts: 176
    3
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Winston Gutkowski wrote:why not create an ExecutionCounter class?


    I have no idea how would you do that. Could you please elaborate ?
     
    Winston Gutkowski
    Bartender
    Posts: 10573
    65
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Shubham Semwal wrote:I have no idea how would you do that. Could you please elaborate?

    Unfortunately it depends on what your requirements are; but at least having a class isolates the problem from the rest of your program.

    A class that can properly "synchronize" access to a file across multiple JVMs is going to be quite tricky, but I suspect it can be done via FileChannel's lock() method. But how "good" it is, or whether there are any easier ways, I don't know.

    And the reason I don't know is that, in 15 years of using Java, I've never had a need for it.
    So my question is: Why do you want an execution counter?

    If we knew a bit more about the "why" to this problem we might be able to offer alternatives.

    Winston
     
    Shubham Semwal
    Ranch Hand
    Posts: 176
    3
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Winston Gutkowski wrote: Why do you want an execution counter?

    Maybe to keep track of how many objects of a particular class has been created. Or how many times a method has been called by different objects.
     
    Stephan van Hulst
    Saloon Keeper
    Posts: 7797
    142
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    That sounds like 'what', not 'why'. I doubt counting the number of objects created, or how often a method is called, is part of your business logic, or a responsibility of the class involved. If you want to do this for debugging, you're better off running a profiler. If you want to use this for statistics, use a logger.
     
    Winston Gutkowski
    Bartender
    Posts: 10573
    65
    Eclipse IDE Hibernate Ubuntu
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Shubham Semwal wrote:Maybe to keep track of how many objects of a particular class has been created...

    I hate to say, but any answer that starts with the word "maybe" sounds like speculation to me.

    As Stephan said, there are already perfectly good tools for doing that sort of stuff - but your original post was asking about when to use static; and the answer is (still) "only if you have a very good reason to".

    And there are good reasons - most of which have been provided in previous posts - but don't go looking for them.
    Java is an Object-Oriented language, so things generally work best with objects ... and static is pretty much the opposite of that.

    Winston
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!