Static Currentspeed Currentspeed Static

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 9

The Java programming language defines the following kinds of variables:

 Instance Variables (Non-Static Fields) Technically speaking, objects store their


individual states in "non-static fields", that is, fields declared without the static
keyword. Non-static fields are also known as instance variables because their values are
unique to each instance of a class (to each object, in other words); the currentSpeed of
one bicycle is independent from the currentSpeed of another.
 Class Variables (Static Fields) A class variable is any field declared with the static
modifier; this tells the compiler that there is exactly one copy of this variable in
existence, regardless of how many times the class has been instantiated. A field defining
the number of gears for a particular kind of bicycle could be marked as static since
conceptually the same number of gears will apply to all instances. The code static int
numGears = 6; would create such a static field. Additionally, the keyword final could
be added to indicate that the number of gears will never change.
 Local Variables Similar to how an object stores its state in fields, a method will often
store its temporary state in local variables. The syntax for declaring a local variable is
similar to declaring a field (for example, int count = 0;). There is no special keyword
designating a variable as local; that determination comes entirely from the location in
which the variable is declared — which is between the opening and closing braces of a
method. As such, local variables are only visible to the methods in which they are
declared; they are not accessible from the rest of the class.
 Parameters You've already seen examples of parameters, both in the Bicycle class and
in the main method of the "Hello World!" application. Recall that the signature for the
main method is public static void main(String[] args). Here, the args variable
is the parameter to this method. The important thing to remember is that parameters are
always classified as "variables" not "fields". This applies to other parameter-accepting
constructs as well (such as constructors and exception handlers) that you'll learn about
later in the tutorial.

 instance variable
 a variable, part of an Object. These might better be called perObject variables since each
instantiated object of this class will have its own private copy of this variable. They are
allocated when the object is allocated via new.
 Static methods may not access the instance variables of their class (or any other class for
that matter), other than via some object reference, e.g. anObject.someField. Static
methods may even access private instance variables in their class via some object
reference.
 class variable
 a static variable in some class. You might better call them perClass variables since there
is only one copy of this variable to serve all objects of the class, not one per object. It is
allocated when the class is first loaded.
static
static variables and methods might better have been called perClass variables and
methods. They inherited this misleading terminology from C++. They are the opposite of
instance variables and methods that work on a particular object.

There is nothing static (unchanging) about them. They don’t cling. They are perfectly
clear, unlike radio signals garbled by static.

They are allocated when the class is loaded. static refers to a method or variable that is
not attached to a particular object, but rather to the class as a whole.

static final when applied to a variable is Javanese for "constant". All static methods are
automatically final. It is not strictly speaking an error to mark them final, but it is
redundant and considered bad form.

static methods work without any this object. static methods are limited to calling other
static methods in the class and to using only static variables. They can call instance
methods only if they use their own object references — not rely on this..

static methods and variable are in a sense inherited, but not in the same strong sense that
instance variables and methods are. You can refer to Dog.bark() as Dalmatian.bark() if no
one has written a Dalmatian.bark(). However, if you use Dog.bark() you always get the
Dog version and if you say Dalmatian.bark() you always get the Dalmatian version.

Newbies tend to overuse static variables. Consider what would happen if your code were
used by several threads simulaneously. With shared static variable they would trip over
each other. With local and instance variables they often would not, even without any
special sychronisation. Sometimes, of course, you do need the globalness of static
variables, but don’t use it where it would make more sense to create a object to track each
chain of calculation.

Static typing
The word static is used in a second context, the opposite of dynamic or runtime type. This
refers to the compile-time declared type of a variable, compared with the run time actual
type it points to. e.g. a Dog variable may point to a Dalmatian object, but not vice versa.
The static type (the type of the reference) is Dog and the dynamic type (the type of the
object) is Dalmatian. You will often hear Java referred to a language with static type
checking. The types of all references are checked for consistency at compile time.

Static Loading
The word static is used in a third context. It refers to ordinary classes explicitly
mentioned in the code. Dynamic classes are loaded on-the-fly using Class.forName
where the class name is constructed as a String.
Static Web Pages
The word static is used in a fourth context. It refers to web pages the server sends out
unchanged. Dynamic pages are modified or even composed from scratch before sending.

Static Nested Classes


Finally, Java has an obscure feature where you can also declare nested classes static. This
does not mean all their methods are static, or that they cannot be instantiated, rather it
means you instantiate the inner classes independently of the main enclosing class. There
is no associated outer class object. Such classes are often called nested static classes.
Non-static inner class objects always have an associated outer class object.

 A class variable is a field declared using the keyword static within a class declaration
(§8.3.1.1), or with or without the keyword static within an interface declaration (§9.3). A class
variable is created when its class or interface is prepared (§12.3.2) and is initialized to a default
value (§4.5.5). The class variable effectively ceases to exist when its class or interface is
unloaded (§12.7).
 An instance variable is a field declared within a class declaration without using the keyword
static (§8.3.1.1). If a class T has a field a that is an instance variable, then a new instance
variable a is created and initialized to a default value (§4.5.5) as part of each newly created
object of class T or of any class that is a subclass of T (§8.1.3). The instance variable effectively
ceases to exist when the object of which it is a field is no longer referenced, after any necessary
finalization of the object (§12.6) has been completed.

Local variables are declared by local variable declaration statements (§14.4). Whenever the flow of
control enters a block (§14.2) or for statement (§14.13), a new variable is created for each local
variable declared in a local variable declaration statement immediately contained within that block or
for statement. A local variable declaration statement may contain an expression which initializes the
variable. The local variable with an initializing expression is not initialized, however, until the local
variable declaration statement that declares it is executed. (The rules of definite assignment (§16)
prevent the value of a local variable from being used before it has been initialized or otherwise assigned
a value.) The local variable effectively ceases to exist when the execution of the block or for statement
is complete.
Static variable, the field is allocated when the class is created. It belongs to the class and not any
object of the class. It is class variable.

Instace variable, the field is allocated when the class is instanciated to the class is called instance
variable or non-static variable

Static variable has only one copy for all the methods in class while instance variable has many
copy.

Class can access only static variable while object can access both class and instance variable.

Question
I'm confused about variables and their scope. What's the difference between a member variable,
and a local variable?

Answer
Simple! A member variable is a variable that belongs to an object, whereas a local variable
belongs to the current scope. Hmm... Still confused?

When we define a class, we can give that class member variables. These variables are members
of that class. Take, for example, the following class declaration.

public class MyClass {


int a;
int b;
}

MyClass has two member variables, a & b. When we define an object instance of MyClass it will
still have two member variables, a & b. We can reference these members using the '.' character.

// Create an instance of MyClass


MyClass obj = new MyClass();

// Assign new values to a & b


obj.a = 1;
obj.b = 65536;

These variables belong to MyClass, and are known as member variables. On the other hand, if
we declare variables inside of a function, we call these local variables. These variables are local
to a particular function, and not publicly accessible. For example, in the following function, we
have no way of accessing the obj variable outside of the main(String[]) function.

public static void main (String args[])


{
        MyClass obj = new MyClass();

        System.out.println ("A" + obj.a);


}

nstance Variables (Non-Static Fields) Technically speaking, objects store their individual states in "non-
static fields", that is, fields declared without the static keyword. Non-static fields are also known as
instance variables because their values are unique to each instance of a class (to each object, in other
words); the currentSpeed of one bicycle is independent from the currentSpeed of another.

# Class Variables (Static Fields) A class variable is any field declared with the static modifier; this tells the
compiler that there is exactly one copy of this variable in existence, regardless of how many times the
class has been instantiated. A field defining the number of gears for a particular kind of bicycle could be
marked as static since conceptually the same number of gears will apply to all instances. The code static
int numGears = 6; would create such a static field. Additionally, the keyword final could be added to
indicate that the number of gears will never change.

# Local Variables Similar to how an object stores its state in fields, a method will often store its
temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field
(for example, int count = 0;). There is no special keyword designating a variable as local; that
determination comes entirely from the location in which the variable is declared — which is between
the opening and closing braces of a method. As such, local variables are only visible to the methods in
which they are declared; they are not accessible from the rest of the class.

Local variables internal to methods are always prefered, since you want to keep each variable's
scope as small as possible. But if more than one method needs to access a variable, then it's
going to have to be an instance variable.

Local variables are more like intermediate values used to reach a result or compute something on
the fly. Instance variables are more like attributes of a class, like your age or name.
Short story: if and only if a variable needs to be accessed by more than one method(or outside of the
class) create it as an instance variables. If you need it only locally, in a single method, it has to be a local
variable. Instance variables are more costly than local variables.
Keep in mind: instance variables are initialized to default values while local variables are not.

Instance variables have separate values for each instance of a class. Class variables
maintain a single shared value for all instances of the class, even if no instance object of
that class exists.

You would use the static keyword to change an instance variable into a class variable.

Both instance and class variables are declared at the class level, not within methods:

public class Foo {


static private int count; // class variable
String name; // instance variable
private void Bar() {
int halfCount; // local variable
}
}

Note also that classes are loaded by classloaders therefore class variables are unique on a
per-classloader basis.
Local/Instance/Class Variables

There are three kinds of Java variables:

1. Local variables are declared in a method, constructor, or block. When a method is entered, an
area is pushed onto the call stack. This area contains slots for each local variable and parameter.
When the method is called, the parameter slots are initialized to the parameter values. When
the method exits, this area is popped off the stack and the memory becomes available for the
next called method. Parameters are essentially local variables which are initialized from the
actual parameters. Local variables are not visible outside the method.
2. Instance variables are declared in a class, but outside a method. They are also called member or
field variables. When an object is allocated in the heap, there is a slot in it for each instance
variable value. Therefore an instance variable is created when an object is created and
destroyed when the object is destroyed. Visible in all methods and constructors of the defining
class, should generally be declared private, but may be given greater visibility.
3. Class/static variables are declared with the static keyword in a class, but outside a method.
There is only one copy per class, regardless of how many objects are created from it. They are
stored in static memory. It is rare to use static variables other than declared final and used as
either public or private constants.

characteristic Local variable Instance variable Class variable

Where In a method, constructor, or In a class, but outside a In a class, but outside a


declared block. method. Typically private. method. Must be declared
static. Typically also
final.

Use Local variables hold values Instance variables hold Class variables are mostly
used in computations in a values that must be used for constants,
method. referenced by more than variables that never change
one method (for example, from their initial value.
components that hold
values like text fields,
variables that control
drawing, etc), or that are
essential parts of an object's
state that must exist from
one method invocation to
another.

Lifetime Created when method or Created when instance of Created when the program
constructor is entered. class is created with new. starts.
Destroyed when there are Destroyed when the
Destroyed on exit. no more references to program stops.
enclosing object (made
available for garbage
collection).

Scope/Visibility Local variables (including Instance (field) variables can Same as instance variable,
formal parameters) are been seen by all methods in but are often declared
visible only in the method, the class. Which other public to make constants
constructor, or block in classes can see them is available to users of the
which they are declared. determined by their class.
Access modifiers (private, declared access:
public, ...) can not be used
with local variables. All local private should be your
variables are effectively default choice in
private to the block in which declaring them. No other
class can see private
they are declared. No part
instance variables. This is
of the program outside of
regarded as the best
the method / block can see choice. Define getter and
them. A special case is that setter methods if the value
local variables declared in has to be gotten or set
the initializer part of a for from outside so that data
statement have a scope of consistency can be
the for statement. enforced, and to preserve
internal representation
flexibility.

Default (also called


package visibility) allows
a variable to be seen by
any class in the same
package. private is
preferable.

public. Can be seen from


any class. Generally a bad
idea.

protected variables are


only visible from any
descendant classes.
Uncommon, and probably
a bad choice.
Declaration Declare before use Declare anywhere at class Declare anywhere at class
anywhere in a method or level (before or after use). level with static.
block.

Initial value None. Must be assigned a Zero for numbers, false for Same as instance variable,
value before the first use. booleans, or null for object and it addition can be
references. May be assigned assigned value in special
value at declaration or in static initializer block.
constructor.

Access from Impossible. Local variable Instance variables should be Class variables are qualified
outside names are known only declared private to with the class name (eg,
within the method. promote information Color.BLUE). They can also
hiding, so should not be be qualified with an object,
accessed from outside a but this is a deceptive style.
class. However, in the few
cases where there are
accessed from outside the
class, they must be qualified
by an object (eg, myPoint.x).

Name syntax Standard rules. Standard rules, but are static public final
often prefixed to clarify variables (constants) are all
difference from local uppercase, otherwise
variables, eg with my, m, or normal naming
m_ (for member) as in conventions. Alternatively
myLength, or this as in prefix the variable with "c_"
this.length. (for class) or something
similar.

You might also like