WHAT'S NEW?

Instance and Local Variables

Instance Variables



Instance Variables are those variables which are defined outside the constructors and methods.

Let see an image describing instance variable.



The area in yellow is of class, anything written inside class but not inside method or constructor will be considered as Instance Variables.


public class Car
{
int tyre;
float petrol;

Car()
{
System.out.println("Inside Car()");
}

public void start()
{
System.out.println("start Car");
}

public void stop()
{
System.out.println("Stop Car");
}
}

Here tyre and petrol are instance variables as they are defined outside constructor or methods but inside class.


Scope of Instance Variables


Instance variables are available throughout the class.
Any method or any constructor in a class can access instance variable.


Initialization of Instance Variable


Instance variables are implicitly initialized to their natural known values, all int to 0,float to 0.0f, String to "" and objects to null.




Local Variables



Local variables are those variables which are defined inside the constructor or methods.
Let see a diagram to describe Local Variables.


The are in blue replicates class, and in gray replicated Constructors and methods, so anything defined inside constructor and method will be considered as Local Variables.


public class Human
{
public void write()
{
Pen p=new Pen();
p.write();
}

}

Here Pen is a local variable to method write() of Human.


Scope of Local Variables.


Local variables are only available inside the method or constructor in which it is defined.

Initialization of Local Variable.


Local variables have to be explicitly initialized, or else you will get an error variable i might not have been initialized.


Even the variable used as an parameter is considered as Local variable of a method.

For example 
public void area(int radius)
{
}

So radius here will be considered as local variable.

Consider a program ,

public class Circle
{
int radius;

public void setRadius(int rad)
{
radius=rad;
}
}

This is a valid code but, the problem here is naming variable differently might cause problems.
For example if the code is implemented in a Nuclear Science Project, rad can be radians.

So changing the code will make it

public class Circle
{
int radius;

public void setRadius(int radius)
{
radius=radius;
}
}
But the code will become error-nous as compiler will get confused and throw Ambiguity error.

So to solve this problem, only way to name instance and local variable same comes with an exception,

 public class Circle
{
int radius;

public void setRadius(int radius)
{
this.radius=radius;
}
}

this keyword replicates the our own  instance, so when any variable is used with this keyword it replicates the instance variable of the class used.

Instance & Local Variables



0 comments:

Post a Comment