Ravenous
Ravenous

Reputation: 356

Declaring class level variables JAVA

Is it possible to declare a class level variable from within a method?

I'm simply trying to create a static counter, but I only want to create it if needed. The class calling it should live longer than the function itself.

My need for this is rare, but I'm interested if it would work.

Upvotes: 1

Views: 2645

Answers (3)

user207421
user207421

Reputation: 310980

'static ... when needed' is a contradiction in terms. The answer is 'no'.

Upvotes: 0

user2813148
user2813148

Reputation:

"Is it possible to declare a class level variable from within a method?"

If literally - yes :) it is possible with method-local classes :

void method() {
    class LocalClass {
        private Object variable;
    }
}

Upvotes: 1

om-nom-nom
om-nom-nom

Reputation: 62835

Not it is not possible to declare class level field, unless you're doing some metaprogramming stuff like insane bytecode level modification that wouldn't pay for itself. All declaration is done at compile time.

Upvotes: 4

Related Questions