Java SE packages, packages, static keywords and code blocks

1. Encapsulation

1.1 Concept of encapsulation
There are three major characteristics of object-oriented programs: encapsulation, inheritance, and polymorphism. In the class and object stage, the main research is on encapsulation characteristics. What is encapsulation? simply put
It’s the shell shielding details.
Encapsulation: organically combine data and methods of operating data, hide the properties and implementation details of the object, and only expose the interface to interact with the object.
1.2 Encapsulated access qualifiers
Generally, the access qualifier we use for encapsulation: pritave

class Student {<!-- -->
    private String name;
    private int age;
    
    public void exam() {<!-- -->
        System.out.println(this.name + "Exam in progress");
    }
}
public class Main {<!-- -->
    public static void main(String[] args) {<!-- -->
        Student student = new Student();
        student.name = "zhangsan";
    }
}

Running error:

Why does this happen? Because the member variable name is modified by pritave in the Student class. This reflects encapsulation.
If you call it directly, it is not allowed. So how should we call this member variable?
We can define a member method in the class and then call this member method to access the member variables. This is allowed. This is an indirect access, how to achieve it? Let’s implement the code:

 public String getName() {<!-- -->
        return name;
    }

    public void setName(String name) {<!-- -->
        this.name = name;
    }

The setName method can modify or assign member variables:

public class Main {<!-- -->
    public static void main(String[] args) {<!-- -->
        Student student = new Student();
        student.setName("zhangsan");
    }
}

Through debugging, you can see that the member variable modified by private in the Student class is assigned from null to “zhangsan”

The getName method can access member variables modified by private.

public class Main {<!-- -->
    public static void main(String[] args) {<!-- -->
        Student student = new Student();
        student.setName("zhangsan");
        System.out.println(student.getName());
    }
}

Through debugging, we can see that member variables modified by private can be accessed through this method.

By calling these two member methods, you can access the member variables modified by pritave in the class.
There is a shortcut key for writing two methods in idea:
After right-clicking:

2. Package

2.1 Concept of package
In the object-oriented system, the concept of a software package is proposed, that is, in order to better manage classes, multiple classes are collected together into a group, called a software package.
Packages have also been introduced in Java. Packages are the embodiment of the encapsulation mechanism for classes, interfaces, etc., and are a good way to organize classes or interfaces. For example, classes in one package do not want to be used by classes in other packages. use. Packages also play an important role: classes with the same name are allowed to exist in the same project, as long as they are in different packages.
2.2 Import classes in packages
In the code, if we have a class that we need to use, we can directly import the package of this class.

public class Test {<!-- -->
    public static void main(String[] args) {<!-- -->
        java.util.Date data = new java.util.Date();
    }

}

This will be troublesome to import, and the code will not be concise enough, and it will be difficult to understand. You can use the import statement to import the package.

import java.util.Date;
public class Test {<!-- -->
    public static void main(String[] args) {<!-- -->
        Date date = new Date();
       //java.util.Date data = new java.util.Date();
    }

}

If you don’t want just this one class, but all the classes in this package, you can import java.util.* like this

import java.util.*;
public class Test {<!-- -->
    public static void main(String[] args) {<!-- -->
        Date date = new Date();
       //java.util.Date data = new java.util.Date();
    }

}

In this way, as long as the classes in the java.util package can be used, we can see what other classes are in this package:

However, we recommend that you explicitly specify the class name to be imported. Otherwise, conflicts are still prone to occur. Because a class is not only in one package, sometimes the content of this class is different in another package. In order for the compiler to serve us better, we try to define a detailed class name instead of a general one. the type.

import java.util.*;
import java.sql.*;
public class Test {<!-- -->
    public static void main(String[] args) {<!-- -->
        Date date = new Date();
       //java.util.Date data = new java.util.Date();
    }

}

Here the Date class compiles and reports an error, so it is better for us to be more specific about the name of the class.

You can use import static to import static methods and fields in the package.

import static java.lang.Math.*;
public class Test {<!-- -->
public static void main(String[] args) {<!-- -->
double x = 30;
double y = 40;
// Static import is more convenient to write.
// double result = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
double result = sqrt(pow(x, 2) + pow(y, 2));
System.out.println(result);
}
}

Note: There is a big difference between import and C++’s #include. C++ must #include to introduce the content of other files, but Java does not require it.
Import is just for convenience when writing code. Import is more similar to C++’s namespace and using.
2.3 Customized package
Basic Rules
Add a package statement at the top of the file to specify which package the code is in.
The package name needs to be specified as unique as possible, usually using the reverse form of the company’s domain name (for example, com.bao.www)
The package name must match the code path. For example, if you create a package of com.bao.www, then there will be a corresponding path com.bao.www to store it.
code.
If a class does not have a package statement, the class is placed in a default package.
Steps:

  1. First create a new package in IDEA: right-click src -> New -> Package:

  2. Enter the package name in the pop-up dialog box, for example: com.bao.www

  3. Create a class in the package, right-click the package name -> New -> Class, and then enter the class name.

    4. At this point you can see that the directory structure on our disk has been automatically created by IDEA:

    5. At the same time, we also saw that at the top of the newly created Test.java file, a package statement appeared:

    2.4 Common packages

  4. java.lang: Commonly used basic classes (String, Object) in the system. This package is automatically imported from JDK1.1 onwards.

  5. java.lang.reflect:java reflection programming package;

  6. java.net: Development kit for network programming.

  7. java.sql: Support package for database development.

  8. java.util: is the tool package provided by java. (Collection class, etc.) Very important

  9. java.io: I/O programming development package.

3.static members

public class Student{<!-- -->
// ...
public static void main(String[] args) {<!-- -->
Student s1 = new Student("Li leilei", "male", 18, 3.8);
Student s2 = new Student("Han MeiMei", "female", 19, 4.0);
Student s3 = new Student("Jim", "male", 18, 2.6);
}
}

Each object will contain a copy of the member variables defined in the Student class (called instance variables), because this information needs to be used to describe
specific students. Now we want to represent the classroom where students attend class. The attributes of this classroom do not need to be stored in each student object, but need to be shared by all students. In Java, members modified by static are called static members or class members. They do not belong to a specific object and are shared by all objects.
3.2static modified member variables
Member variables modified by static are called static member variables. The biggest feature of static member variables is that they do not belong to a specific object, they are shared by all objects, and they belong to the class.
[Static member variable characteristics]

  1. It does not belong to a specific object. It is an attribute of the class. It is shared by all objects and is not stored in the space of an object.
  2. It can be accessed through objects or class names, but it is generally recommended to use class names for access.
  3. Class variables are stored in the method area
  4. The life cycle follows the life of the class (that is, it is created when the class is loaded and destroyed when the class is unloaded)
    3.3 static modified member methods
    Generally, the data members in the class are set to private, and the member methods are set to public. After setting, what will happen to the classRoom attribute in the Student class?
    What about access outside the class?
public class Student{<!-- -->
private String name;
private String gender;
private int age;
private double score;
private static String classRoom = "Bit306";
// ...
}
public class TestStudent {<!-- -->
public static void main(String[] args) {<!-- -->
System.out.println(Student.classRoom);
}
}
Compilation failed:
Error:(10, 35) java: classRoom is private access control in extend01.Student

How should static attributes be accessed?
In Java, member methods modified by static are called static member methods. They are methods of the class and are not unique to an object. Static members are generally accessed through static methods.
[Static method characteristics]

  1. It does not belong to a specific object, it is a class method
  2. It can be called through the object or through the class name.static method name (…). It is more recommended to use the latter.
  3. You cannot access any non-static member variables in a static method
  4. Any non-static method cannot be called in a static method, because non-static methods have this parameter, and this reference cannot be passed when calling in a static method.
    3.4static member variable initialization
    Note: Static member variables are generally not initialized in the constructor. What is initialized in the constructor is the instance attributes related to the object. There are two types of initialization of static member variables: in-place initialization and static code block initialization.
  5. Initialize in place
    In-place initialization refers to: giving the initial value directly when defining
public class Student{<!-- -->
private String name;
private String gender;
private int age;
private double score;
private static String classRoom = "Bit306";
// ...
}

4. Code block

4.1 Concept and classification of code blocks
A section of code defined using {} is called a code block. According to the position and keywords defined in the code block, it can be divided into the following four types:
normal code block
building blocks
static block
Synchronized code blocks (will be discussed later in the multi-threading section)
4.2 Ordinary code blocks
Ordinary code block: a code block defined in a method.

public class Main{<!-- -->
public static void main(String[] args) {<!-- -->
{<!-- --> //Use {} definition directly, ordinary method block
int x = 10;
System.out.println("x1 = " + x);
}
int x = 100;
System.out.println("x2 = " + x);
}
}

4.3 Constructing code blocks
Building block: Building block: A block of code defined in a class (without modifiers). Also called: instance code block. Construction code blocks are generally used to initialize instance member variables

public class Student{<!-- -->
//Instance member variables
private String name;
private String gender;
private int age;
private double score;
public Student() {<!-- -->
System.out.println("I am Student init()!");
}
//Example code block
{<!-- -->
this.name = "bit";
this.age = 12;
this.sex = "man";
System.out.println("I am instance init()!");
}
public void show(){<!-- -->
System.out.println("name: " + name + " age: " + age + " sex: " + sex);
}
}
public class Main {<!-- -->
public static void main(String[] args) {<!-- -->
Student stu = new Student();
stu.show();
}
}

4.4 Static code block
Code blocks defined using static are called static code blocks. Generally used to initialize static member variables.

public class Student{<!-- -->
private String name;
private String gender;
private int age;
private double score;
private static String classRoom;
//Example code block
{<!-- -->
this.name = "bit";
this.age = 12;
this.gender = "man";
System.out.println("I am instance init()!");
}
// static code block
static {<!-- -->
classRoom = "bit306";
System.out.println("I am static init()!");
}
public Student(){<!-- -->
System.out.println("I am Student init()!");
}
public static void main(String[] args) {<!-- -->
Student s1 = new Student();
Student s2 = new Student();
}
}

4.5 Regarding the execution order of static code blocks, instantiated code blocks and constructor methods:

class Student {<!-- -->
        public String name;

    static {<!-- -->
        System.out.println("Student::static");
    }
    {<!-- -->
        System.out.println("instantiation code implementation");
    }
    public Student(String name) {<!-- -->
        this.name = name;
        System.out.println("Constructor method implementation");
    }
}
public class Test {<!-- -->
    public static void main(String[] args) {<!-- -->
        Student student = new Student("xiaowang");
    }
}


Implement the static code block first, then the instantiation code block, and finally the constructor method.
Instantiate an object again and implement it again:

class Student {<!-- -->
        public String name;

    static {<!-- -->
        System.out.println("Student::static");
    }
    {<!-- -->
        System.out.println("instantiation code implementation");
    }
    public Student(String name) {<!-- -->
        this.name = name;
        System.out.println("Construction method implementation");
    }
}
public class Test {<!-- -->
    public static void main(String[] args) {<!-- -->
        Student student = new Student("xiaowang");
        System.out.println("================");
        Student student1 = new Student("wangss");
    }
}


The static code block is not executed because the static code block is only executed once.

Notes
No matter how many objects are generated, the static code block will only be executed once.
Static member variables are attributes of the class, so they are opened up and initialized when the JVM loads the class.
If a class contains multiple static code blocks, when compiling the code, the compiler will execute (merge) them in the order defined.
Instance code blocks are only executed when the object is created

End of this chapter…