Hi,
Anyone explain me what is static method in Java?
Thanks
Printable View
Hi,
Anyone explain me what is static method in Java?
Thanks
There are two types of methods.
- Instance methods are associated with an object and use the instance variables of that object. This is the default.
- Static methods use no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is unusual. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this are the many utility methods in the predefined Math class.
Calling static methods
There are two cases.
Called from within the same class
Just write the static method name. Eg,
Called from outside the classCode:// Called from inside the MyUtils class
double avgAtt = mean(attendance);
If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified. Eg,
If an object is specified before it, the object value will be ignored and the the class of the object will be used.Code:// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance);
static variables are classes variables not instance variables .They are instantianted only once for a class.They are initialised at class load time.
Static method can be referenced with the name of the name of the particular object of that class. That's how the library methods like System.out.println works.
Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.
The use of a static method suffers from the following restrictions:
1. A static method can only call other static methods.
2. A static method must only access static data.
3. A static method cannot reference to the current object using keywords super or this.
Static Methods:
a. In a file context, it means that the function can be called only within the file scope.
b. In a class context, it means that you can invoke a method of a class without having to instantiate an object. However note that in static methods, you can only manipulate variables that are declared as static, and not other variables.
Code:static means that it cannot be changed
static method can be referanced using super or this:cool: