aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes non-static methods Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "non-static methods" Watch "non-static methods" New topic
Author

non-static methods

Jama Mohmoud
Greenhorn

Joined: May 09, 2003
Posts: 7
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

Joined: May 09, 2003
Posts: 7
meant to say without instantiating an object in the non-static method.
--------------------------------------------------------------------------------
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
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

Joined: May 17, 2003
Posts: 2
but still cam we use static variables in non-static methods
Anupam Sinha
Ranch Hand

Joined: Apr 13, 2003
Posts: 1088
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 ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: non-static methods