Java Reference
In-Depth Information
/* Only the instance variable n1 is in scope here. The local variable n2
is also in scope here, which you are ignoring for our discussion for now */
int n1 = 20; /* A local variable n1 */
/* Both, instance variable n1 and local variable n1 are in scope here.
We are ignoring n2 for now. */
int n3 = n1; // Assigns 20 to n3
}
}
The above code assigns the value of the n1 variable to n2 inside the m1() method. You have not declared the local
variable n1 at the time you assigned the value of n1 to n2 . At this time, only the instance variable n1 is in scope. When
you assign n1 to n3 , at that time both instance variable n1 and local variable n1 are in scope. The values assigned to
n2 and n3 depend on the name-hiding rule. When two variables with the same names are in scope, the local variable
is used.
Does it mean that you cannot declare an instance/class variable and a local variable with the same name and use
both at the same time? The answer is no. You can declare an instance/class variable and a local variable with the same
name. The only thing you need to know is how to refer to the instance/class variable if its name is hidden by a local
variable. You will learn about referring to the hidden instance/class variables in the next section.
Instance Method and Class Method
In the previous sections, I discussed two types of class fields: instance variables and class variables. A class can have
two types of methods: instance methods and class methods. Instance methods and class methods are also called
non-static methods and static methods, respectively.
An instance method is used to implement behavior for the instances (also called objects) of the class. An instance
method can only be invoked in the context of an instance of the class.
A class method is used to implement the behavior for the class itself. A class method always executes in the
context of a class.
The static modifier is used to define a class method. The absence of the static modifier in a method
declaration makes the method an instance method. The following are examples of declaring some static and
non-static methods:
// A static or class method
static void aClassMethod() {
// method's body goes here
}
// A non-static or instance method
void anInstanceMethod() {
// method's body goes here
}
Recall that a separate copy of an instance variable exist for each instance of a class, whereas only one copy of a
class variable exists, irrespective of the existence of the number of instances (possibly zero) of the class.
 
Search WWH ::




Custom Search