Doubt in using Static key word
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Sriram_Sundararajan
Posted On:   Friday, April 18, 2003 02:57 AM

hi all i can use static key word in variable,block and methods. Static vairable,block calls only one time in the JVM. static methods can be accessed directly without creating the instances. My doubt is in the usage of static while creating the instance of the class static A a = new A(); What is the advantage by using the above statement in my program over my ordinary instantiation for ex:- A a = new A(); i have tried the above two statements in my program i haven't seen any difference in that. can anyone plz clear my doubts regarding this. regards sri    More>>

hi all

i can use static key word in variable,block and methods. Static vairable,block calls only one time in the JVM. static methods can be accessed directly without creating the instances.


My doubt is in the usage of static while creating the instance of the class


static A a = new A();

What is the advantage by using the above statement in my program over my ordinary instantiation for ex:-


A a = new A();


i have tried the above two statements in my program i haven't seen any difference in that.



can anyone plz clear my doubts regarding this.


regards


sri

   <<Less

Re: Doubt in using Static key word

Posted By:   Stephen_McConnell  
Posted On:   Friday, April 18, 2003 04:59 AM

This depends upon the scope of the variable.


If it is an instance or class variable, the purpose of having a static variable is that the value of that static variable persists from instance to instance of an object of that class.


This can be a good thing and a bad thing.


If you want to share a value between instances this is one way to do it (Not the safest, but one way to do it). However, if you are doing any threading, this is not a very good idea unless you are using it as a semaphore and synchronize your code.


There is no difference in the between what happens in your code if you are dealing with just one instance of the class at a time... Try it when you have three or four instances all accessing and changing that static variable.


Static methods are useful for utility methods in a class... When you want to have a handle to a method on a class without having to instantiate an object. They are also the thing that makes the singleton design pattern work...


I had lots of trouble understanding the value of static variables and objects when I was first learning Java, but now I use the technique all the time.


Good question... Hope this helps.


Stephen McConnell

About | Sitemap | Contact