Example code:
public class MyClass {
public static double globallyVisibleDbl = 42.69;
public static final int globallyVisibleInt = 42;
//blah blah rest of code
}
and there is double type variable and constant, both inside a class.
But when i'll try put those two outside class, for example before the class and just after import statements -- like there's allowed in C or C++ thanks to #define token [value] directive -- I get error:
import com.something.*;
public static double globallyVisibleDbl = 42.69;
public static final int globallyVisibleInt = 42;
public class MyClass {
//some code
}
Why is so?
Because there is no "global scope" in java. All variables must be declared inside a method or a class. When you declare your variables above the class declaration, java does not relate it to the class just because it is in the same file.
The syntax of Java is largely derived from C++. Unlike C++, which combines the syntax for structured, generic, and object-oriented programming, Java was built almost exclusively as an object-oriented language. All code is written inside a class, and everything is an object, with the exception of the primitive data types (e.g. integers, floating-point numbers, boolean values, and characters), which are not classes for performance reasons.
@See Java_syntax
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With