Static methods are useful if you have only one instance (situation, circumstance) in which you intend to use this method, and you do not need several copies (objects). For example, if you write a method that registers with one and only one website, downloads weather data, and then returns values, you can write it as static, because you can hard-code all the necessary data in the method and you wonโt have multiple copies or copies. You can then access the method statically using one of the following:
MyClass.myMethod(); this.myMethod(); myMethod();
Non-static methods are used if you intend to use your method to create multiple copies. For example, if you want to download meteorological data from Boston, Miami and Los Angeles, and if you can do this from your method without individually setting the code for each individual location, then you access the method non-statically
MyClass boston = new MyClassConstructor(); boston.myMethod("bostonURL"); MyClass miami = new MyClassConstructor(); miami.myMethod("miamiURL"); MyClass losAngeles = new MyClassConstructor(); losAngeles.myMethod("losAngelesURL");
In the above example, Java creates three separate objects and memory cells from the same method, which you can get individually using the "boston", "miami" or "losAngeles" link. You cannot access any of the above statically, because MyClass.myMethod (); It is a general reference to a method, and not to individual objects created by a non-static link.
If you are faced with a situation where the method of accessing each location or the method of returning data is quite different, you cannot write the โone size fits allโ method without jumping over many hoops, you can better accomplish your task by writing three separate static methods: one for each location.
VikingGlen Jul 06 '13 at 20:40 2013-07-06 20:40
source share