Saturday, 24 August 2013

Instance Variables (Non-Static Fields)

Objects of a class store their individual states in "non-static fields" i.e.; the fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique for each instance(object) of the class.

currentSpeed of one Bicycle is independent from the currentSpeed of another Bicycle.

Class Variables (Static Fields)

All field declared with the static modifier are called class variables. The static modifier tells the compiler that only one copy of this variable will exist, regardless of how many times the class has been instantiated(how many times the object of the class being created).

A field defining the number of gears for bicycle could be marked as static since conceptually the same number of gears will apply to all the instances.

Code Example:
static int numGears = 6; You can also add the keyword final to indicate that the number of gears will never change.

Local Variables

A method stores its temporary state in local variables, similar to how an object stores its state in fields.

Syntax – Declaring a field:
int count = 0; There is no special keyword to declare a variable as local. The location of declaration of the variable determines whether it is a local variable or not.

A variable declared in the method body is local to the method. A local variable will only be visible to the methods in which it is declared. A local variable is not accessible from the rest of the class.

In Java Language, the
main method has the args variable as the parameter.

Note that, the parameters are always classified as "variables" and not "fields". This applies to other parameter-accepting constructs as well (such as constructors)

Get Ebooks delivered to your email id


Subscribe to our channel


Powered by Blogger.

Home | Contact Us | DMCA | Terms of Service | Privacy | Advertise

Maven Scientists