I want to know the difference between class variable and variable declared inside the constructor. For example:
class A {
int a;
}
vs
class A {
public A() {
int a;
}
}
I want to know the difference between class variable and variable declared inside the constructor. For example:
class A {
int a;
}
vs
class A {
public A() {
int a;
}
}
when you do
class A {
int a;
}
the integer a can be accessed by any other instance method in the class A, and any child object (some package restrictions) of that class as well...
so the main difference is the scope of that variable
on the other hand... when you do
public A() {
int a;
}
the variable a is out of that scope as soon as the constructor returns...
In
class A {
int a;
}
the variable can be used anywhere in the class
But, in
class A {
public A() {
int a;
}
}
the variable a
can only be accessed inside the function A()
So
class A {
int a;
public printA() {
Log.i("TEST", a); // will work fine
}
}
but
class A {
public printA() {
int a;
Log.i("TEST", a); // will work fine
}
public void printA1() {
...
...
Log.i("TEST", a); // will throw an error
}
}
in class A { int a; }
the variable a
is shared in the whole class, by all the methods you will implement in it (and to other package's classes, int that precise case).
As for class A { public A() { int a; } }
the variable a
is only accessible within the constructor's scope. That means it is destroyed when the constructor returns.
In the first class, a
is heap-allocated, and in the other case it is stack-allocated.
Class variables are 2 types
Constructors, instance methods can access both static and non static variables, but constructor variables are local variables like method variables, we can't access outside of the constructor.