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

non-static methods

 
Jama Mohmoud
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All.
Can someone please explain why I'm able to call static variable from a non-static method with instansiating an object in the non-static method?
thanks

public class Commission
{
private static double salesFigure = 56.0;
private static double commRate;

public void multiply()
{ // here i'm calling the static variables
// and code compiles fine. why?
double bonus = salesFigure * commRate;
System.out.println("Here it is " + total );
}


public static void main( String [] args )
{
Commission m = new Commission();
m.multiply();
}
}
 
Jama Mohmoud
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
meant to say without instantiating an object in the non-static method.
--------------------------------------------------------------------------------
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
First of all instansiating an object is not required to access the static var because static vars are class variables. You can instansiate an object and use it if you wish and can also use the classname.staticvariable eg. double bonus = Commission.salesFigure * Commission.commRate;
But in your code both the method and variable the method acts upon is in the same code so in there you can simply use the var name as you have used.
Though you can use the classinstance.staticvar convention (using class instance to refer to the static var) but its not recommended and its much better to use classname.staticvar(using class name to refer to the static var).
[ May 16, 2003: Message edited by: Anupam Sinha ]
 
mani kadiyala
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but still cam we use static variables in non-static methods
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
but still cam we use static variables in non-static methods

Yes you can.
Using static variables in non-static methods is ok but you can not declare a static variable in a method(static or non-static).
Condsider this :

[ May 17, 2003: Message edited by: Anupam Sinha ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic