Examine the following. Does this code compile? Pay particular attention to N
.
public class UnitTestBad { int N = 10; public static long factorial( ) { long fct = 1; for ( int j=1; j<=N; j++ ) fct *= j; return fct; } public static void main (String[] args ) { System.out.println( "factorial of " + N + ": " + factorial() ); } }
No, the code does not compile.
The code declares an instance variable N
.
An instance variable is part of an object of the type described by the class.
So if we had an object of type BadUnitTest
,
then that object would have an instance variable N
.
But this code does not construct such an object.
So there is no N
that the static method
factorial()
can see and so the compiler produces an error message:
UnitTestBad.java:15: error: non-static variable N cannot be referenced from a static context System.out.println( "factorial of " + N + ": " + factorial( N ) ); ^
A class variable is one that is part of the class, but not part of any object. Class variables are also called static variables. Static methods can use the static variables of their class.
To declare a static variable, use the word static
in the declaration.
Now the variable is part of the class and is visible
throughout the class unless local declarations shadow it.
(See chapter 51.)
However, using static variables like this violates the idea of modularity and should be avoided.
Does the following code fix the problem?
public class UnitTestBad { static int N = 10; public static long factorial( ) { long fct = 1; for ( int j=1; j<=N; j++ ) fct *= j; return fct; } public static void main (String[] args ) { System.out.println( "factorial of " + N + ": " + factorial() ); } }