Static?

Started by
10 comments, last by LessThanJoe 20 years, 6 months ago
This is probably fairly simple for you guys, but I'm new to both java and static classes so this is kind of a double whammy. I'm trying to write a class that does a bunch of conversions for another program. Since this class doesn't need to store any data, I want to make all the functions static. So I did this, now when I am trying to compile my driver program, I'm getting the error: "U:\Menu.java:384: non-static method TemperatureConversions() cannot be referenced from a static context" Here is the source for the main method
public static void main(String [] args)
	{	
		int input = 7;
		
		while (input != 0)
		{
			System.out.println("Choose the type of conversion or enter 0 to exit.");
			System.out.println("1: Temperature Conversions");
			System.out.println("2: Mass Conversions");
			System.out.println("3: Length Conversions");
			System.out.println("4: Volume Conversions");
			System.out.println("5: Pressure Conversions");
			System.out.println("6: Energy Conversions");
			
			input = Keyboard.readInt();
			
			switch(input)
			{
				case 1:
				{
					TemperatureConversions();
					break;
				}
				case 2:
				{
					MassConversions();
					break;
				}
				case 3:
				{
					LengthConversions();
					break;
				}
				case 4:
				{
					VolumeConversions();
					break;
				}
				case 5:
				{
					PressureConversions();
					break;
				}
				case 6:
				{
					EnergyConversions();
					break;
				}
				default:
				{
					System.out.println("Please choose a number between 0 and 6.");
					break;
				}
			} // end switch

		} // end while loop

	} // end main function


and here is the source for the function that is getting the error

   
	public void TemperatureConversions()
	{
		ClearScreen();
		
		int choice = 3;
		double input = 0;
				
		while (choice != 0)
		{
			System.out.println("Choose your conversion type or press 0 to return to the main menu.");
			System.out.println("1: Celsius to Fahrenheit");
			System.out.println("2: Fahrenheit to Celsius");
		 	choice = Keyboard.readInt();
		 	
		 	switch(choice)
		 	{
		 		// case 0 handles itself, but must exist to prevent the default from running

		 		// when the user chooses to return to the main menu

		 		case 0:
		 			break;
		 		case 1:
		 		{
		 			System.out.println("Enter the temperature in Celsius");
		 			input = Keyboard.readDouble();
		 			System.out.println("That is " + Conversion.CelsiusToFahrenheit(input) + " degrees Fahrenheit.");
		 			break;
		 		}
		 		case 2:
		 		{
		 			System.out.println("Enter the temperature in Fahrenheit");
		 			input = Keyboard.readDouble();
		 			System.out.println("That is " + Conversion.FahrenheitToCelsius(input) + " degrees Celsius.");
		 			break;
		 		}
		 		default:
		 		{
		 			System.out.println("Please enter a number between 0 and 2.");
		 			break;
		 		}
		 	} // end switch

		 } // end while loop

	} // end TemperatureConversion

[edited by - lessthanjoe on October 7, 2003 8:55:02 PM]
Advertisement
I''m more of a C++ person than a java person, so I''ve only had a lil bit of Java experience, but doesn''t the temp conversion function have to be declared staticly as well, like

public static void TemperatureConversions

that''s how I''m interpretting your error at least.
Write more poetry.http://www.Me-Zine.org
The functions need to be declared static also.

Additionally, they should be invoked using

Classname.MethodName() to avoid any ambiguity.
--what''s it all about?
Well, the functions that are static are the Conversion.SomethingToSomething else stuff. TemperatureConversion and Main are in the same class. I made tempconvert static and it works, but I was under the impression there was a way to call a static function from a non-static class

ie this should work. What''s the difference between this and my functions?
double cube (double number){    return Math.Pow(number, 3);}



Also, I''m supprised no one noticed the error I had with the condition for the while loop in temp convert. Oh well, too late now...muhaha.
Here's the difference: static members are class members while non-static members are object members. Notice that I say members here because the same applies to methods (functions) as well as attributes (variables). Now, check this:

1. All static members are automatically allocated in static memory (not heap or stack) at program initialization (I can't remember whether or not Java automatically initializes them as well).

2. Non-static members don't get allocated or initialized until you declare an object of that type. So, you can't call a non-static method or reference a non-static variable from a static method because the non-static members may not actually exist.

3. Whenever you create an objects of a given class type, each object of that type gets its own copy of any non-static members (methods as well as attributes), while they all share the exact same copies of any members (again, methods as well as attributes).

4. Since static data is initialized without the need to create any objects of that class type, any public static data can be accessed without creating an object of that type, i.e
ClassName.StaticMethodName().

Note, that the answer to your question lies mainly in #2.

Here is a simple example of static usage:

public class TestClass{   static count = 0;   TestClass(){      count++;   }   public static getCount(){      return count;   }}public class TestApp{   public static void main(String [] args){      System.out.println("# of test objects: " +          TestClass.getCount());  //called statically without an object      TestClass [] objects = new TestClass[10];      System.out.println("# of test objects: " +          TestClass.getCount());  //called statically without an object      System.out.println("# of test objects: " +         objects[0].getCount());  //called by an object      System.out.println("# of test objects: " +         objects[5].getCount());  //called by an object   }}Output:# of test objects: 0# of test objects: 10# of test objects: 10# of test objects: 10



Note that this is a way to achieve global access to functions in Java, but requires you to think a little more about what you're doing that just slapping a global on it an doing whatever.

peace and (trance) out

Mage

Edit: Added the object-call test cases.

[edited by - Mage2k on October 7, 2003 10:07:09 PM]
---------------------------------------------------There are 10 kinds of people in the world:Those that understand binary, and those that dont...Mage
ok, I'm fairly certin I got that much. How does that explain why it's not letting me call another function. I'll give a shorter demo of my code to see if it makes sense

public class Convert {    public Convert()    {    }    public static double StaticMethod(double num)    {       return (num * 42);    }}public class Drvier{    public void function ()    {       System.out.println( Convert.StaticMethod(1) );    }    public static void main( String [] args)    {        function();    }}


Then the error would be "non-static method function() cannot be referenced from a static context"

edit: source closing tag

[/source]

[edited by - lessthanjoe on October 7, 2003 12:27:03 AM]
The short answer is like this. When you declare a method as static, you''re saying that there doesn''t have to be an instance of that object in order to call that method. Therefore, it can''t access any non-static variables or call any non-static functions. This is because the compiler has know way of knowing whether or not those non-static functions access non-static variables themselves. The only way it can know for certain that the function you are calling is doesn''t access any non-static variables, is if it is static too.
How then, does a non-static method make a call to anything in the Math class...

I''m so confused.
Non-static methods CAN call static methods.
Static methods CANNOT call non-static methods.

Math.pow is static.
quote:Original post by Tibre
The short answer is like this. When you declare a method as static, you''re saying that there doesn''t have to be an instance of that object in order to call that method. Therefore, it can''t access any non-static variables or call any non-static functions. This is because the compiler has know way of knowing whether or not those non-static functions access non-static variables themselves. The only way it can know for certain that the function you are calling is doesn''t access any non-static variables, is if it is static too.
Ummm... not quite. I think a better way to word it is that you can only call non-static methods with a valid reference to an object that has been created with new. Static methods are class operations and non-static methods are object operations.

In Java in particular, it is very important to have an understanding of how static works because it is at the very heart of a Java program runs. Ever wonder why it is necessary to declare main as static? The reason is because it must be called before any objects have been created, including an object of the class to which main belongs. Note also that there is nothing preventing you from creating objects inside static methods and then calling non-static methods on those objects from within that static method -- if that was the case you could only ever call static methods because you start from main.

LessThanJoe, to answer your last question, you can not call function from within main because even though you are inside a method that belongs to Driver, the rule still applies that you can not call a non-static method on Driver until you have an object created of type Driver at which time you will be calling function on that object (btw, even in examples, using the word function for a function name is a bad idea, use someFunction() or foo() or some such...).

This would work:

public class Convert{   public Convert(){ }       public static double StaticMethod(double num){             return (num * 42);   }}public class Drvier{public void function(){   System.out.println( Convert.StaticMethod(1) );       }       public static void main( String [] args){      Driver driverObject = new Driver();       driverObject.function();       }}


peace and (trance) out

Mage
---------------------------------------------------There are 10 kinds of people in the world:Those that understand binary, and those that dont...Mage

This topic is closed to new replies.

Advertisement