Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do Java doesn't allow to initialize variables or constants outside classes?

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?

like image 362
spaffy Avatar asked May 04 '26 11:05

spaffy


2 Answers

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.

like image 181
TheZuck Avatar answered May 06 '26 02:05

TheZuck


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

like image 42
M. Abbas Avatar answered May 06 '26 00:05

M. Abbas