-1

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;
    }
}
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
Dhinesh
  • 141
  • 1
  • 4
  • 18

4 Answers4

1

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...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
1

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
    }
}  
mrid
  • 5,782
  • 5
  • 28
  • 71
0

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.

TDk
  • 1,019
  • 6
  • 18
0

Class variables are 2 types

  1. Static variables - Class level variables
  2. Non static variable - Instance variable

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.

trinath
  • 433
  • 1
  • 5
  • 19