Buzz HT
Buzz HT

Reputation: 27

Why can't we define (assign a value) a variable (field) after it is declared in a class?

In a normal class,

public class MyClass {
    int a =12; 
} 

works fine.

But,

public class MyClass {
    int a =12;
    int b;
    b=13;
} 

this gives a compilation error.

I know I am trying to access a field without using an object of that class, so I even tried this->

public class MyClass {
    int a =12;
    int b;
    MyClass m= new MyClass();
    m.b=13;
} 

but even this doesn't seem to work.

I can accept the fact that this is how things work and move on. But does anyone know the logic behind this?

Thank you in advance.

Upvotes: 0

Views: 1126

Answers (2)

Sara
Sara

Reputation: 623

int a = 12;

This is a variable declaration with initialisation.

b=13;

This is an assignment; a statement; it cannot be part of the declaration. It has to be part of the constructor or method.

It is how Java object definition works.

  • variable/field declarations
  • constructors
  • methods (static or non-static)

Upvotes: 1

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79055

You can do it in one of the following two ways:

  1. Use the initialization block as follows:

    int b;
    {
        b = 13;
    }
    
  2. Do the following in the constructor:

    b = 13;
    

Check https://docs.oracle.com/javase/tutorial/java/javaOO/initial.html to learn more about it.

Upvotes: 0

Related Questions