Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

non-static method calling static variable

 
Jama Mohmoud
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 270
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic