Home >Java >javaTutorial >An explanation of Java's access modifiers and variable scope

An explanation of Java's access modifiers and variable scope

高洛峰
高洛峰Original
2017-01-24 15:34:351738browse

Java access modifiers (access control characters)
Java uses modifiers to control access permissions and other functions of classes, properties and methods, usually placed at the front of the statement. For example:

public class className {
  // body of class
}
private boolean myFlag;
static final double weeks = 9.5;
protected static final int BOXWIDTH = 42;
public static void main(String[] arguments) {
  // body of method
}

Java has many modifiers, which are divided into access modifiers and non-access modifiers. This section only introduces access modifiers, non-access modifiers will be introduced later.

Access modifiers are also called access control characters, which refer to keywords that can control the usage rights of classes, member variables, and methods.

In object-oriented programming, access control characters are a very important concept, which can be used to protect access to classes, variables, methods and constructors.

Java supports four different access rights:

An explanation of Javas access modifiers and variable scope

public: public

Classes, methods, and structures declared as public Methods and interfaces can be accessed by any other class.

If several public classes that access each other are distributed in different packages, you need to import the package where the corresponding public class is located. Due to class inheritance, all public methods and variables of a class can be inherited by its subclasses.

The following method uses public access control:

public static void main(String[] arguments) {
  // body of method
}

The main() method of the Java program must be set to public, otherwise, the Java interpreter will not be able to run the kind.
protected: protected

Variables, methods and constructors declared as protected can be accessed by any other class in the same package, and can also be accessed by subclasses in different packages.

The protected access modifier cannot modify classes and interfaces. Methods and member variables can be declared protected, but member variables and member methods of interfaces cannot be declared protected.

Subclasses can access the methods and variables declared with the protected modifier, thus protecting unrelated classes from using these methods and variables.

The following parent class uses the protected access modifier, and the subclass overloads the bark() method of the parent class.

public class Dog{
  protected void bark() {
    System.out.println("汪汪,不要过来");
  }
}
class Teddy extends Dog{ // 泰迪
  void bark() {
    System.out.println("汪汪,我好怕,不要跟着我");
  }
}

If the bark() method is declared as private, classes other than Dog will not be able to access this method. If bark() is declared as public, all classes can access this method. If we only want the method to be visible to subclasses of its class, declare the method as protected.
private: private

The private access modifier is the most restrictive access level, so methods, variables and constructors declared as private can only be accessed by the class to which they belong, and classes and interfaces cannot be declared as private.

Variables declared as private access types can only be accessed by external classes through the public Getter/Setter methods in the class.

The use of private access modifier is mainly used to hide the implementation details of the class and protect the data of the class.

The following classes use private access modifiers:

public class Dog{
  private String name;
  private int age;
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
}

In the example, the name and age variables in the Dog class are private variables, so other classes cannot obtain them directly. and set the value of this variable. In order to enable other classes to operate the variable, two pairs of public methods are defined, getName()/setName() and getAge()/setAge(), which are used to get and set the value of the private variable.

this is a keyword in Java, which will be discussed in this chapter. You can click Java this keyword detailed explanation preview.

When defining methods to access private variables in a class, it is customary to name them as follows: add "get" or "set" in front of the variable name, and capitalize the first letter of the variable. For example, the method to get the private variable name is getName(), and the method to set the name is setName(). These methods are often used and have specific names, called Getter and Setter methods.
Default: Do not use any keywords

Attributes and methods declared without any modifiers are visible to classes in the same package. The variables in the interface are implicitly declared as public static final, and the access rights of the methods in the interface are public by default.

As shown in the following example, classes, variables and methods are defined without any modifiers:

class Dog{
  String name;
  int age;
  
  void bark(){ // 汪汪叫
    System.out.println("汪汪,不要过来");
  }
  void hungry(){ // 饥饿
    System.out.println("主人,我饿了");
  }
}

Access Control and Inheritance

Please note the following Rules for method inheritance (readers who do not understand the concept of inheritance can skip here, or click Java inheritance and polymorphism preview):
Methods declared as public in the parent class must also be public in the child class.
Methods declared as protected in the parent class are either declared as protected or public in the subclass. Cannot be declared private.
Methods declared with the default modifier in the parent class can be declared private in the subclass.
Methods declared as private in the parent class cannot be inherited.
How to use access control characters

The access control characters allow us to easily control the permissions of the code:
When you need to make the class you wrote to be accessed by all other classes, you can add the class The access control character is declared as public.
When you need to make your class accessible only to classes in your own package, you can omit the access control character.
When you need to control member data in a class, you can set the member data access control code in this class to public, protected, or omitted.

The scope of Java variables
In Java, the scope of variables is divided into four levels: class level, object instance level, method level, and block level.

类级变量又称全局级变量或静态变量,需要使用static关键字修饰,你可以与 C/C++ 中的 static 变量对比学习。类级变量在类定义后就已经存在,占用内存空间,可以通过类名来访问,不需要实例化。

对象实例级变量就是成员变量,实例化后才会分配内存空间,才能访问。

方法级变量就是在方法内部定义的变量,就是局部变量。

块级变量就是定义在一个块内部的变量,变量的生存周期就是这个块,出了这个块就消失了,比如 if、for 语句的块。块是指由大括号包围的代码,例如:

{
  int age = 3;
  String name = "www.weixueyuan.net";
  // 正确,在块内部可以访问 age 和 name 变量
  System.out.println( name + "已经" + age + "岁了");
}
// 错误,在块外部无法访问 age 和 name 变量
System.out.println( name + "已经" + age + "岁了");

说明:
方法内部除了能访问方法级的变量,还可以访问类级和实例级的变量。
块内部能够访问类级、实例级变量,如果块被包含在方法内部,它还可以访问方法级的变量。
方法级和块级的变量必须被显示地初始化,否则不能访问。

演示代码:

public class Demo{
public static String name = "微学苑"; // 类级变量
public int i; // 对象实例级变量
// 属性块,在类初始化属性时候运行
{
int j = 2;// 块级变量
}
public void test1() {
int j = 3; // 方法级变量
if(j == 3) {
int k = 5; // 块级变量
}
// 这里不能访问块级变量,块级变量只能在块内部访问
System.out.println("name=" + name + ", i=" + i + ", j=" + j);
}
public static void main(String[] args) {
// 不创建对象,直接通过类名访问类级变量
System.out.println(Demo.name);
 
// 创建对象并访问它的方法
Demo t = new Demo();
t.test1();
}
}

运行结果:

微学苑
name=微学苑, i=0, j=3

更多An explanation of Javas access modifiers and variable scope相关文章请关注PHP中文网!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn