Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Scope of an identifier. Local variables. Access control.

Types of variables. Declarations. | More on operators and expressions | Numeric promotions | Objects and references | The class String | Useful examples | Defining attributes of objects | Defining operations on objects (methods) | Defining methods of object creation (constructors) | Static members |


Читайте также:
  1. Access labels
  2. Access to private and protected members of the containing type
  3. Accessibility
  4. Accessibility domains
  5. Accession and coronation
  6. Broad government access to private data: Perhaps someday
  7. Chapter 2. History of Random-access memory

The scope of an identifier is the region of the program within which it can be referred to using a simple name.

 

Class members (fields and methods) can be referred to from any method of the class, no matter where in the class body the declaration of the member occurs.
A field initializer can refer only to the fields of the class which were declared earlier.

 

Each method may declare its own variables (or constants). The scope of their identifiers is local - it starts at the place of declaration and ends with the method body (at the closing brace of the method). Such variables are called local variables. Method parameters have the same scope. In fact, parameters are local variables.
The scope of a variable declared inside the local block (set of instructions enclosed with braces) is the rest of the block in which the declaration appears.

Consider the following class:

class A { int a; void method1() { int b;... } void method2() { int c;... }}

Inside the method method1 we can access the variables a and b and the method method2. Inside the method method2 we can access the variables a and c and the method method1. The variable c cannot be referred to inside the method method1, and similarly the variable b cannot be referred to inside the method method2.

Inside a constructor or a method a class field identifier may be shadowed.
For example:

class A { int a; void method() { int a = 0; // the field a is shadowed by the local variable a a = a + 10; // the local variable a is used here this.a++; // the class field is used here }}


The local variable x is declared inside the method method(). It has the same name as the class field, therefore the local variable shadows the class field. The expression a in the method() refers to (denotes) the value of the local variable. The class field may be accessed using the qualified name: this.a.

 

In Java local variables cannot be shadowed in local blocks.

 

Thus the definition:

class A {
....
void method() {
int a;
{
int a;
...
}
}
}

is erroneous.


Contrary to class variables (fields), local variables are not automatically initialized. The value of a local variable is unspecified until it is initialized by an initializer or assignment.

Local variables should be explicitly initialized.

 


What about accessing members of a class from another class?
It is determined by access modifiers.
The accessibility of a class member may be:


We have already learned some of the reasons for using access modifiers. Note how they restrict access to class members:

import javax.swing.*; public class Pair { private int a; private int b; public String name; public Pair(int x, int y) { a = x; b = y; } private String makeString() { return name + " " + a + " and " + b; } public void show() { JOptionPane.showMessageDialog(null, makeString()); // 6 }} class Test { public static void main(String[] args) { Pair p = new Pair(17,20); p.name = "Pair of numbers"; // 1 p.a = 1; // 3 System.out.println(p.makeString()); // 4 p.show(); // 5 }}

Compilation generates the following errors:

Pair.java:29: a has private access in Pair
p.a = 1; // 3
^
Pair.java:30: makeString() has private access in Pair
System.out.println(p.makeString()); // 4
^
2 errors


Note that:


Classes may be declared public. Such classes may be accessed by any code. If a class is not declared public, then it may be accessed only from within the package in which it is declared.

To declare a public class the modifier public must be used:

public class Pair {
...
}

A source file may contain at most one public class. The name of this class must be identical as the name of the file.

 


Дата добавления: 2015-11-16; просмотров: 61 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Packages and imports| Structure of a program. Running an application.

mybiblioteka.su - 2015-2024 год. (0.008 сек.)