user12394078
user12394078

Reputation: 63

passing value to member variable in java

Why can we do this:

class A{int a=5;}

but are not allowed to do this:

class A {
     int a;
     a=5;       
}

Upvotes: 1

Views: 82

Answers (1)

Alireza Jamali
Alireza Jamali

Reputation: 317

just put it inside a block then.

class A {
     int a;
     {a=5;}       
}

An initialization block will run every time you make in instance of the class e.g.

new A();

this is of course between two other initializations related to creating a new instance. first is the field's initializations like when you declare a field with a value.

int a = 25;

then the block initialization

{
  a = 5;
}

then the constructor:

A() {
    a = 6;
}

Upvotes: 2

Related Questions