javascript
Brief description  about Online courses   join in Online courses
View Hemant  pugaliya 's Profile

Why do we need static function overloading as shown below?

class Calculate
{ public static double res;
public static void calc(int x,int y)
{ res=x y;
}
public static void calc(float x,float y)
{ res=x*y;}
public static void calc(double x,double y)
{ res=x-y; }
public static void main(String[] args)
{ System.out.println("Calling and printing result of calc(5,3)( both integer variables)");
calc(5,3);
System.out.println("Result: " res);
System.out.println("Calling and printing result of calc(5.0,3.0)( both double variables)");
calc(5.0,3.0);
System.out.println("Result: " res);
System.out.println("Calling and printing result of calc(5.0f,3.0f)( both float variables)");
calc(5.0f,3.0f);
System.out.println("Result: " res);
}
}
if i remove the static from this code except for the one in main it gives the folowing errors
non static method calc(int,int)cannot be referenced from static context
calc(5,3);
non static variable res cannot be referenced from static context
System.out.print("Result= " res);

and similar errors for next function calls and print statements.
When do we need to declare methods and variables static??are there any set of rules and exception to it??




Asked by Hemant pugaliya | Jul 2, 2013 |  Reply now
Replies (1)
View java teacher 's Profile
The static variables are allocated memory at the class loading time,and the memory is allocated only once.

Now if you have a static variable inside a method,then that variable comes under the method's scope,not class's scope,and JVM is unable to allocate memory to it,because a method is called by the help of class's object,and that is at runtime,not at class loading time.

It is said the memory reference is same - when we say a variable as static, means it maintains it as constant.

Ok.
Jul 23, 2013