• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

non-static method calling static variable

 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 270
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
She'll be back. I'm just gonna wait here. With this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic