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

An explanation of Java's access modifiers and variable scope

Jan 24, 2017 pm 03:34 PM
java

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
}
Copy after login

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
}
Copy after login

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("汪汪,我好怕,不要跟着我");
  }
}
Copy after login

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;
  }
}
Copy after login

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("主人,我饿了");
  }
}
Copy after login

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 + "岁了");
Copy after login

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

演示代码:

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();
}
}
Copy after login

运行结果:

微学苑
name=微学苑, i=0, j=3
Copy after login

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


Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles