wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes non-static method calling static variable Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "non-static method calling static variable" Watch "non-static method calling static variable" New topic
Author

non-static method calling static variable

Jama Mohmoud
Greenhorn

Joined: May 09, 2003
Posts: 7
Can someone please help me understand this?
why am I able to call static variable from a non-static method, but not the other way around. here are the codes.
public class Commission
{
private static double salesFigure = 56.0;
private static double commissionRate = 34.0;
private static int commRate = 34;

public void multiply()
{
double total = salesFigure * commissionRate * commRate;
System.out.println("Here is the total " + total );
}
public static void main( String [] args )
{
Commission m = new Commission();
m.multiply();
}
}
but the following code doesn't compile.
public class Commission
{
private double salesFigure = 56.0;
private double commissionRate = 34.0;
private int commRate = 34;

public static void multiply()
{
double total = salesFigure * commissionRate * commRate;
System.out.println("Here is the total " + total );
}
public static void main( String [] args )
{
Commission m = new Commission();
m.multiply();
}
}
thanks in advance.
Yi Meng
Ranch Hand

Joined: May 07, 2003
Posts: 270
Static variables are actually class attributes, the class holds exactly one copy of the static variables. All instance references or just the class name refer to the same copy of the class-hold variable. That's why non-static method can access static variables through instance references.
Non-static variables are attributes of a specific instance. Every instance has its own copy of such variables. A static method could be called without any instance of the class object and in such cases, the method cannot access the non-static variables(Or if can, then whose copy to use???).
hope it helps


Meng Yi
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: non-static method calling static variable
 
Similar Threads
Need help with methods
non-static methods
calculating real estate commissions
calculating commission
Third Overloaded method not compiling