Hello,
I have question regarding static variables and methods. we all know static variables and methods accessed by ClassName.StaticMethod
or ClassName.StaticVariable. But, I want to know that In Programs or any application, In which situation, we should make any method or variable as static. and why ?
Static methods and variables belong to the class, not the instance. This means that you can access it with no need to create an object of class using ClassName.staticVariable of ClassName.staticMethod() constructions.
I know that to call static method or static variables we don't need to create any object. we can call them with Class Name. but, if I develop any application or project, some situation occurs when i need to call static method or static variable i use. but, what are those situation. can you give me an example ? so, i can get better idea ....
Rishabh Shah wrote:can you give me an example ? so, i can get better idea ....
A variable which maintains the number of times a page has been viewed. In this case you have to use a static variable. If you use an instance variable here you will not get the correct count.
The use of static variables in real time projects are : Ticket Reservatio System in Railways or Busstations. The passenger ticket number is static it is going to increase with the perticular serial number.
In this scenario also the static variables we can use.
If the static variable value can not reinitialize.
Rishabh Shah wrote:its been written that
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
Singleton s3 = Singleton.getInstance();
it means that the object is created once only, but, it is reference by s1,s2,s3....is it so ?
Rishabh Shah wrote:its been written that
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
Singleton s3 = Singleton.getInstance();
it means that the object is created once only, but, it is reference by s1,s2,s3....is it so ?
Campbell Ritchie wrote:Agree, but beware: many people nowadays think singletons are not a good design pattern; indeed some people say "singleton antipattern".
Campbell, Could you please explain this in detail?