Java SE classes and objects (detailed explanation with pictures and text)

About java classes and objects, we need to grasp several key points!

1. Class definition and object instantiation

2. Use of member variables and member methods in classes

3. The entire initialization process of the object

4.Packaging characteristics

5. Code blocks

Table of contents

1. Preliminary understanding of object-oriented

1.1 What is object-oriented

1.2 Object-oriented and process-oriented 

 1.2.1 Traditional dishwashing process

1.2.2 Modern dishwashing process

2. Class definition and objects 

 2.1 Simple understanding of categories

2.2 Class definition format 

2.3 Example exercises

2.3.1 Define a dog class 

2.3.2 Define a student class

3. Instantiation of classes

 3.1 What is instantiation

3.2 Description of classes and objects

 4. this reference

 4.1 Why is there a this reference?

4.2 What is this reference?

4.3 Characteristics of this reference 

5. Object construction and initialization

5.1 How to initialize objects 

5.2 Construction method

5.2.1 Concept

5.2.2 Features

5.3 Default initialization

5.4 In-place initialization

6. Packaging

6.1 Concept of encapsulation

6.2 Access qualifiers

6.3 Package extension package

6.3.1 The concept of package

6.3.2 Importing classes in packages

6.3.3 Custom packages

 6.3.5 Common packages

7. static members

 7.1 Let’s talk about students again

7.2 static modified member variables 

 7.3 static modified member methods 

7.4 Initialization of static member variables

8. Code blocks

8.1 Concept and classification of code blocks

8.2 Common code blocks

8.3 Constructing code blocks

8.4 Static code blocks


1. Preliminary understanding of object-oriented

1.1 What is object-oriented

First of all, we all know that Java is an object-oriented language (Object Oriented Program, OOP for short). In the object-oriented world, everything is an object. Object-oriented is an idea that is used to solve problems and mainly relies on the interaction between objects to complete one thing. The object-oriented thinking is designed into the program, which is in line with our human understanding of things, and is helpful for the design, expansion and maintenance of large programs!

1.2 Object-oriented and process-oriented 

 1.2.1 Traditional dishwashing process

 

 Note: (The picture comes from the Internet, if there is any infringement, please contact us to delete it)

Dai mantle ---> Water release ---> < a i=4>Howan ---> Housei Keisei ---> ---> Disinfection Clawsui ---> sabukiwan 

The traditional method:focuses on the process of washing dishes,even if one link is missing.

And different dishes and chopsticks have different washing methods, which will be very troublesome to deal with. If you want to wash quilts and furniture in the future, that is another way. Writing code in this way willmake future expansion or maintenance troublesome.

1.2.2 Modern dishwashing process

 Note: (The picture comes from the Internet, if there is any infringement, please contact us to delete it)

There are four objects in total:person, bowl, dish soap, dishwasher.  

The entire dishwasher process: people put the bowls into the dishwasher, pour the dishwashing liquid, start the dishwasher, and the dishwasher will complete the dishwashing process and disinfect it.

The whole process is mainly:The interaction between four objects: people, bowls, dishwashing liquid, and dishwashers. People do not need to care about how the dishwasher washes them. How to sterilize bowls.

 

 Handle it in an object-oriented manner and do not pay attention to the process of the dishwasher. Specifically, how the dishwasher washes and disinfects the dishes. Users do not need to care about the series of processes. They only need to put the bowl in the dishwasher, add detergent, and turn on the switch. It is completed through the interaction between objects

2. Class definition and objects 

JAVA is object-oriented programming, which focuses on objects, and objects are actually entities in real life, such as dishwashers. But our computer does not know a dishwasher, so developers need to tell the computer what a dishwasher is.

  Note: (The picture comes from the Internet, if there is any infringement, please contact us to delete it)

The picture above is a simple description of the dishwasher. This process is to abstract the object (entity) of the dishwasher (re-recognition of a complex thing) , but these simplified abstract results are still not recognized by computers, so what should we do? Developers can use some object-oriented programming language to describe, such as: java, c++, etc.

 2.1 Simple understanding of categories

What is a class? The class is used to describe an entity (object). It mainly describes what attributes (shape, size, etc.) the entity (object) has, and which Function (what can it do?), after the description is completed, the computer can recognize it

For example: xx dishwasher, which is a brand, can be regarded as a category in Java.
Attributes: product brand, model parameters, rated power, appearance size... 
Function: dishwashing, disinfection, storage... .

 In Java language, how do we define the above washing machine class?

2.2 Class definition format 

 ! When defining a class in java, you need to use the class keyword. The specific syntax is as follows

// 创建类
class ClassName{
    field; // 字段(属性) 或者 成员变量
    method; // 行为 或者 成员方法
}

 class is the keyword that defines the class, ClassName is the name of the class, and {} is the body of the class.

 The content contained in the class is called the member of the class. Attributes are mainly used to describe classes, and are called member attributes of the class or class member variables . member methods of the class mainly describe the functions of the class, which are called Methods.

class WashMachine{
    public String brand; // 品牌
    public String type; // 型号
    public double weight; // 重量
    public double length; // 长
    public double width; // 宽
    public double height; // 高
    public String color; // 颜色

    public void washBowls(){ // 洗碗
        System.out.println("洗碗功能");
    }

    public void disinfect(){ // 消毒
        System.out.println("消毒功能");
    }

    public void setTime(){ // 定时
        System.out.println("定时功能");
    }
}

Use Java language to define the washing machine class in the computer. After javac compilation, a .class file is formed, which can be recognized by the computer based on the JVM.
Note:
Please note that the class name should be defined in camel case
The writing method before members should be public
The method written here does not contain the static keyword

 

2.3 Example exercises

2.3.1 Define a dog class 

class PetDog {
    // 狗的属性
    public String name;//名字
    public String color;//颜色

    // 狗的行为
    public void barks() {
        System.out.println(name + ": 旺旺~~");
    } 

    public void wag() {
        System.out.println(name + ": 摇尾巴~~~");
    }
}

2.3.2 Define a student class

public class Student{
    public String name;
    public String gender;
    public short age;
    public double score;
    public void DoClass(){}
    public void DoHomework(){}
    public void Exam(){}
}

Notes:
1. Generally, only one class is defined in a file
2. The class where the main method is located generally needs to be modified with public (note : Eclipse will look for the main method in the public-modified class by default)
3. The public-modified class must have the same name as the file
4. Do not modify it easily The name of the class modified by public. If you want to modify it, modify it through the development tool

 

3. Instantiation of classes

 3.1 What is instantiation

Defining a class is equivalent to defining a new type,Similar to int and double, except that int and double are built-in types that come with the Java language, while classes are user-defined new types, such as the above-mentioned: PetDog class and Student class. They are all classes (a newly defined type). With these custom types, you can use these classes to define instances (or objects). The process of creating an object using a class type is called instantiation of the class, adopted in javanew. instantiate the objectKeyword, match the class name to

In this way, we have completed the instantiation and created a dog named Goudan, with green hair, barking, and wagging its tail. 

public class Main{
    public static void main(String[] args) {
        PetDog dog = new PetDog(); //通过new实例化对象
        dog.name = "狗蛋";
        dog.color = "绿色";
        dog.barks();
        dog.wag();
    }
}

 Notes
        The new keyword is used to create an instance of an object.
        Use . to access the properties and methods in the object.
        The same class can create multiple instances.

3.2 Description of classes and objects

1. A class is just a model-like thing, used to describe an entity and limit the members of the class.
2. A class is a self-defined type. Can be used to define variables.
3. A class can instantiate multiple objects. The instantiated objects occupy actual physical space and store class member variables
4. Make an analogy. Class is like a house design. We have designed whether the house has three bedrooms and one living room, whether it has a large independent balcony, and whether it has a large courtyard. The instantiation object is equivalent to decorating the existing three bedrooms, one living room, large balcony, etc. on the house design drawing. For example: these three bedrooms are all decorated in Japanese style.

A class is an abstract thing, like a design drawing; and the object instantiated by a class is something more specific, like a house constructed based on the design drawing.
 

 

  Note: (The picture comes from the Internet, if there is any infringement, please contact us to delete it)

 4. this reference

 4.1 Why is there a this reference?

 Let’s first look at an example of a date class:

public class Date {

    public int year;
    public int month;
    public int day;

    public void setDay(int y, int m, int d){
        year = y;
        month = m;
        day = d;
    }

    public void printDate(){
        System.out.println(year + "/" + month + "/" + day);
    }

    public static void main(String[] args) {
        // 构造三个日期类型的对象 a b c
        Date a = new Date();
        Date b = new Date();
        Date c = new Date();
        // 对d1,d2,d3的日期设置
        a.setDay(2020,1,11);
        b.setDay(2020,1,12);
        c.setDay(2020,1,13);
        // 打印日期中的内容
        a.printDate();
        b.printDate();
        c.printDate();
    }
}

 The above code defines a date class, and then creates three objects in the main method, and sets and prints the objects through the member methods in the Date class. The overall logic of the code is very simple and there are no problems.
But after careful consideration, there are two questions:

1. The formal parameter name is accidentally the same as the member variable name:

public void setDay(int year, int month, int day){
    year = year;
    month = month;
    day = day;
}

So who assigns values ​​to whom in the function body? Member variable to member variable? Parameter to parameter? Parameters to member variables? Member variables to parameters? I guess I can’t even figure it out.


2. All three objects are calling the setDate and printDate functions, but there is no description of the objects in these two functions.How do the setDate and printDate functions know which one is being printed? What about the object's data?

 This has to be mentioned!

 

4.2 What is this reference?

This reference points to the current object (the object that calls the member method when the member method is running). All member variable operations in the member method are accessed through this reference. It's just that all operations aretransparent to the user, that is, the user does not need to pass it, the compiler automatically completes it.

public class Date {

    public int year;
    public int month;
    public int day;

    public void setDay(int year, int month, int day){
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public void printDate(){
        System.out.println(this.year + "/" + this.month + "/" + this.day);
    }
}

Note: this refers to the object on which the member method is called.

public static void main(String[] args) {
    Date d = new Date();
    d.setDay(2020,9,15);
    d.printDate();
}

hered and this refer to < /span>Memory spaceThe same block

4.3 Characteristics of this reference 

1. The type of this: corresponds to the class type reference, that is, which object is called is the reference type of that object
2. this can only be used in "Used in member method"
3. In "member method", this can only be referenced The current object cannot refer to other objects
4. this is the first hidden parameter of the "member method", and the compiler will automatically pass it. During execution, the compiler will be responsible for passing the reference of the calling member method object to the member method, and this will be responsible for receiving
 

5. Object construction and initialization

5.1 How to initialize objects 

We all know that when defining alocal variable inside a Java method, it must be initialized, otherwise the compilation will fail

public static void main(String[] args) {
    int a;
    System.out.println(a);
} 

// Error:(22, 24) java: 可能尚未初始化变量a

It is very simple to make the above code compile. Just set an initial value for a before officially using a.

If it is an object:

public static void main(String[] args) {
    Date d = new Date();
    d.printDate();
    d.setDate(2021,6,9);
    d.printDate();
} 


// 代码可以正常通过编译

You need to call the SetDate method written before to set the specific date into the object. Through the above examples, we found two problems:
1. Each time the object is created, the SetDate method is called to set the specific date. It's more troublesome. How should the object be initialized?
2. Local variables must be initialized before they can be used. Why can a field still be used without a value after it is declared?

This involves Construction method

5.2 Construction method

5.2.1 Concept

The constructor (also called a constructor) is a specialmember method, and the name must Same as the class name, it is automatically called by the compiler when the object is created, and is only called once during the entire object's life cycle.
 

public class Date {
    public int year;
    public int month;
    public int day;
    // 构造方法:
    // 名字与类名相同,没有返回值类型,设置为void也不行
    // 一般情况下使用public修饰
    // 在创建对象时由编译器自动调用,并且在对象的生命周期内只调用一次
    public Date(int year, int month, int day){
        this.year = year;
        this.month = month;
        this.day = day;
        System.out.println("Date(int,int,int)方法被调用了");
    }

    public void printDate(){
        System.out.println(year + "-" + month + "-" + day);
    }

    public static void main(String[] args) {
        // 此处创建了一个Date类型的对象,并没有显式调用构造方法
        Date d = new Date(2021,6,9); // 输出Date(int,int,int)方法被调用了
        d.printDate(); // 2021-6-9
    }
}

Note: The function of the constructor is to initialize the members of the object and is not responsible for opening up space for the object.


5.2.2 Features

1. The name must be the same as the class name 2. There is no return value type, and setting it to void will not work 3. It is automatically called by the compiler when creating an object, and is only called once during the life cycle of the object (equivalent to a person’s birth, each person Can only be born once) 4. The constructor can beoverloaded (users provide constructors with different parameters according to their own needs method)



 

public class Date {
    public int year;
    public int month;
    public int day;

    // 无参构造方法
    public Date(){
        this.year = 1900;
        this.month = 1;
        this.day = 1;
    }

    // 带有三个参数的构造方法
    public Date(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public void printDate(){
        System.out.println(year + "-" + month + "-" + day);
    }

    public static void main(String[] args) {
        Date d = new Date();
        d.printDate();
    }
}

The above two constructors have the same name but different parameter lists, so they constitutemethod overloading


5. If the user does not explicitly define it, the compiler will generate a default constructor. The generated default constructor must be No ginseng.

public class Date {

    public int year;
    public int month;
    public int day;

    public void printDate(){
        System.out.println(year + "-" + month + "-" + day);
    }

    public static void main(String[] args) {
        Date d = new Date();
        d.printDate();
    }
}

There is no constructor defined in the above Date class, and the compiler will generate a constructor without parameters by default.

Note: Once the user defines the constructor, the compiler will no longer generate it.

public class Date {

    public int year;
    public int month;
    public int day;

    public Date(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }

    public void printDate(){
        System.out.println(year + "-" + month + "-" + day);
    }

    public static void main(String[] args) {
    // 如果编译器会生成,则生成的构造方法一定是无参的
    // 则此处创建对象是可以通过编译的
    // 但实际情况是:编译期报错
        Date d = new Date();
        d.printDate();
    }
} 

/*
Error:(26, 18) java: 无法将类 extend01.Date中的构造器 Date应用到给定类型;
需要: int,int,int
找到: 没有参数
原因: 实际参数列表和形式参数列表长度不同
*/

6. In the constructor, you can call other constructors through this to simplify the code.

public class Date {

    public int year;
    public int month;
    public int day;

    // 无参构造方法--内部给各个成员赋值初始值,该部分功能与三个参数的构造方法重复
    // 此处可以在无参构造方法中通过this调用带有三个参数的构造方法
    // 但是this(1900,1,1);必须是构造方法中第一条语句
    public Date(){
        //System.out.println(year); 注释取消掉,编译会失败
        this(1900, 1, 1);
        //this.year = 1900;
        //this.month = 1;
        //this.day = 1;
    } 

        // 带有三个参数的构造方法
    public Date(int year, int month, int day) {
        this.year = year;
        this.month = month;
        this.day = day;
    }
}

Note:
  1. this(...) must be the first statement in the constructor 2. It cannot form a cycle

public Date(){
    this(1900,1,1);
}

public Date(int year, int month, int day) {
    this();
}

 /* 
无参构造器调用三个参数的构造器,而三个参数构造器有调用无参的构造器,形成构造器的递归调用
编译报错:Error:(19, 12) java: 递归构造器调用
*/

7. In most cases, use public to modify it. In special cases, it will be private Modification
 

5.3 Default initialization

The second question raised above: Why do local variables have to be initialized when used, but member variables do not need to be?

public class Date {

    public int year;
    public int month;
    public int day;

    public Date(int year, int month, int day) {
    // 成员变量在定义时,并没有给初始值, 为什么就可以使用呢?
        System.out.println(this.year);
        System.out.println(this.month);
        System.out.println(this.day);
    }

    public static void main(String[] args) {
        // 此处a没有初始化,编译时报错:
        // Error:(24, 28) java: 可能尚未初始化变量a
        // int a;
        // System.out.println(a);
        Date d = new Date(2021,6,9);
    }
}

To understand this process, you need to know something about what happens behind the new keyword:
 

Date d = new Date(2021,6,9);

It is just a simple statement at the program level. There are many things that need to be done at the JVM level. Here is a brief introduction:
1. Check whether the class corresponding to the object is loaded. If not, then load
2. Allocate memory space for the object
3. Handle concurrency security issues
For example: multiple threads apply for objects at the same time , the JVM must ensure that the space allocated to the object does not conflict
4. Initialize the allocated space
That is: the object space is After applying, the members contained in the object have already set their initial values, such as:

5. Set the object header information
6. Call the constructor method and assign values ​​to each member of the object

5.4 In-place initialization

When declaring a member variable, the initial value is directly given.

public class Date {
    public int year = 1900;
    public int month = 1;
    public int day = 1;

    public Date(){
    }

    public Date(int year, int month, int day) {
    }

    public static void main(String[] args) {
        Date d1 = new Date(2021,6,9);
        Date d2 = new Date();
    }

}

Note: After the code is compiled, the compiler will add all these statements for member initialization to each constructor.
 

6. Packaging

6.1 Concept of encapsulation

The 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? To put it simply, it iscase shielding details
  For example: a complex device like a washing machine only provides users with: power on and off, water delivery volume, and washing time. , spin-drying time, etc., allowing users to interact with the washing machine and complete laundry tasks. But in fact, what really works in a washing machine is the outer cylinder, the inner cylinder, the rotating shaft, the drum bearings, etc.

  Note: (The picture comes from the Internet, if there is any infringement, please contact us to delete it)

For washing machine users, there is no need to care about how its internal core components operate. Therefore, manufacturers put a shell on the washing machine to cover up the internal implementation details, and only open the control buttons to the outside so that users can interact with the washing machine.

And packaging is also such a process

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.
 

6.2 Access qualifiers

Encapsulation is mainly implemented in Java through classes and access rights:Classes can combine data and methods of encapsulating data, which is more consistent Human cognition of things, and access permissions are used to control whether methods or fields can be used directly outside the class.

There are four access qualifiers provided in Java:

Note: (The picture comes from the Internet, if there is any infringement, please contact us to delete it) 

For example:
public: can be understood as a person’s appearance characteristics, which can be seen by everyone
default: for members of the same family (same person) package) is not a secret, it is private to others
private: only you know it, no one else knows


[Explanation]
   protected is mainly used in inheritance, and the inheritance part is introduced in detail
   default permission refers to: the default permission when nothing is written
   In addition to limiting the visibility of members in a class, access permissions can also control the visibility of the class

public class Computer {
    private String cpu; // cpu
    private String memory; // 内存
    public String screen; // 屏幕
    String brand; // 品牌---->default属性
    public Computer(String brand, String cpu, String memory, String screen) {
        this.brand = brand;
        this.cpu = cpu;
        this.memory = memory;
        this.screen = screen;
    }

    public void Boot(){
        System.out.println("开机~~~");
    }

    public void PowerOff(){
        System.out.println("关机~~~");
    }

    public void SurfInternet(){
        System.out.println("上网~~~");
    }

}
public class TestComputer {
    public static void main(String[] args) {
        Computer p = new Computer("HW", "i7", "8G", "13*14");
        System.out.println(p.brand); // default属性:只能被本包中类访问
        System.out.println(p.screen); // public属性: 可以任何其他类访问
        //System.out.println(p.cpu); //private属性:只能在Computer类中访问,不能被其他类访问
    }
}

Note: Generally, member variables are set to private, and member methods are set to public.
 

6.3 Package extension package

6.3.1 The 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, which is called a software package. Somewhat similar to a directory. For example: In order to better manage the songs on your computer, a good way is to put songs with the same attributes under the same file, or you can also classify the music in a certain folder in more detail.

For example:
 

Then subdivide rap, rock music, folk music, and light music.

For example:

 Packages have also been introduced in Java. Packages are the embodiment of encapsulation mechanisms for classes, interfaces, etc. , It is a good way to organize classes or interfaces, etc.For example: classes in one package do not want to be used by classes in other packages. 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.

6.3.2 Importing classes in packages

Java has provided many ready-made classes for us to use. For example, the Date class: you can use java.util.Date to import a> java.util The Date class in this package.

public class Test {
    public static void main(String[] args) {
        java.util.Date date = new java.util.Date();
        // 得到一个毫秒级别的时间戳
        System.out.println(date.getTime());
    }
}

But this way of writing is more troublesome. 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();
        // 得到一个毫秒级别的时间戳
        System.out.println(date.getTime());
    }
}

If you need to use other classes in java.util , you can use import java.util. *

import java.util.*;

public class Test {
    public static void main(String[] args) {
        Date date = new Date();
        // 得到一个毫秒级别的时间戳
        System.out.println(date.getTime());
    }
}

But it is more recommended to explicitly specify the class name to be imported. Otherwise, conflicts are still prone to occur.

import java.util.*;
import java.sql.*;

public class Test {
    public static void main(String[] args) {
        // util 和 sql 中都存在一个 Date 这样的类, 此时就会出现歧义, 编译出错
        Date date = new Date();
        System.out.println(date.getTime());
    }
}


// 编译出错
Error:(5, 9) java: 对Date的引用不明确
java.sql 中的类 java.sql.Date 和 java.util 中的类 java.util.Date 都匹配

In this case you need to use the full class name

import java.util.*;
import java.sql.*;

public class Test {
    public static void main(String[] args) {
        java.util.Date date = new java.util.Date();
        System.out.println(date.getTime());
    }
}

You can useimport staticto 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;
        // 静态导入的方式写起来更方便一些.
        // 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: import and C++’s#include The difference is huge. C++ must #include to include the contents of other files, but Java does not. import is just to make it more convenient when writing code. import is more similar to C++'s namespace andusing
 

6.3.3 Custom packages

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 The name is usually the reverse form of the company's domain name (for examplec.b.a ).
  The package name should be the same as the code path Match. For example, if you create a package of c.b.a , then there will be a corresponding path c.b.a to store 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 c.b.a
 

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

6.3.4 Examples of package access rights control

The Computer class is located in the com.bit.demo1 package, and the TestComputer is located in the com.bit.demo2 package: 

package com.bit.demo1;

public class Computer {
    private String cpu; // cpu
    private String memory; // 内存
    public String screen; // 屏幕
    String brand; // 品牌
    public Computer(String brand, String cpu, String memory, String screen) {
        this.brand = brand;
        this.cpu = cpu;
        this.memory = memory;
        this.screen = screen;
    }
    public void Boot(){
        System.out.println("开机~~~");
    }
    public void PowerOff(){
        System.out.println("关机~~~");
    }
    public void SurfInternet(){
        System.out.println("上网~~~");
    }
} 
///
package com.bite.demo2;
import com.bite.demo1.Computer;

public class TestComputer {
    public static void main(String[] args) {
        Computer p = new Computer("HW", "i7", "8G", "13*14");
        System.out.println(p.screen);
        // System.out.println(p.cpu); // 报错:cup是私有的,不允许被其他类访问
        // System.out.println(p.brand); // 报错:brand是default,不允许被其他包中的类访问
    }
}

// 注意:如果去掉Computer类之前的public修饰符,代码也会编译失败

 6.3.5 Common packages

1. java.lang: Commonly used basic classes (String, Object) in the system. This package is automatically imported from JDK1.1 onwards.
2. java.lang.reflect:java reflection programming package;
3. java.net: Network programming development package.
4. java.sql: Support package for database development.
5. java.util: is a tool package provided by java. (Collection classes, etc.) Very important
6. java.io: I/O programming development kit.
 

7. static members

 7.1 Let’s talk about students again

Use the student class introduced in the previous article to instantiate three objects s1, s2, and s3. Each object has its own unique name, gender, age, grade point and other member information. This information is used to describe different students. As follows:

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

Suppose three students are in the same class, then they must be in the same classroom. Since they are in the same classroom, can we add a member variable to the class to save the classroom where the students are in class? The answer is no.


The member variables previously defined in the Student class will be included in each object (called instance variables), because This information is needed 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.
 

7.2 static modified member variables 

statically modified member variables are called static member variables. The biggest feature of static member variables: does not belong to a specific object. Is shared by all objects.

[Characteristics of static member variables]
1. It does not belong to a specific object, but is an attribute of the class. It is shared by all objects and is not stored in the space of a certain object< /span>3. Class variables are stored in the method area< /span>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)
2. It can be accessed either through the object or the class name, but it is generally recommended to use the class name to access it

public class Student{
    public String name;
    public String gender;
    public int age;
    public double score;
    public static String classRoom = "Bit306";
    // ...
    public static void main(String[] args) {
        // 静态成员变量可以直接通过类名访问
        System.out.println(Student.classRoom);
        Student s1 = new Student("Li leilei", "男", 18, 3.8);
        Student s2 = new Student("Han MeiMei", "女", 19, 4.0);
        Student s3 = new Student("Jim", "男", 18, 2.6);
        // 也可以通过对象访问:但是classRoom是三个对象共享的
        System.out.println(s1.classRoom);
        System.out.println(s2.classRoom);
        System.out.println(s3.classRoom);
    }
}

Run the above code in debugging mode, and then you can see in the monitoring window that the static member variables are not stored in a specific object.

 7.3 static modified member methods 

Generally, the data members in a class are set to private, and the member methods are set to public. After setting, how can the classRoom attribute in the Student class be accessed 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);
    }
}

 编译失败:
Error:(10, 35) java: classRoom 在 extend01.Student 中是 private 访问控制

How should the static attribute 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.
 

public class Student{
    // ...
    private static String classRoom = "Bit306";
    // ...
    public static String getClassRoom(){
        return classRoom;
    }
}

public class TestStudent {
    public static void main(String[] args) {
        System.out.println(Student.getClassRoom());
    }
}

Output: Bit306


[Static method characteristics]
1. It does not belong to a specific object, but is a class method
2. It can be called through an object or Called through class name.static method name (...), it is more recommended to use the latter
3. Any non-static member variables cannot be accessed in static methods
 

public static String getClassRoom(){
    System.out.println(this);
    return classRoom;
} 
// 编译失败:Error:(35, 28) java: 无法从静态上下文中引用非静态 变量 this

public static String getClassRoom(){
    age += 1;
    return classRoom;
} 
// 编译失败:Error:(35, 9) java: 无法从静态上下文中引用非静态 变量 age

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.
 

public static String getClassRoom(){
    doClass();
    return classRoom;
} 
// 编译报错:Error:(35, 9) java: 无法从静态上下文中引用非静态 方法 doClass()

7.4 Initialization of static member variables

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

1. In-place initialization
In-place initialization means: giving the initial value directly during definition
 

public class Student{
    private String name;
    private String gender;
    private int age;
    private double score;
    private static String classRoom = "Bit306";
    // ...
}

2. Static code block initialization
So what is a code block? Keep reading :)

8. Code blocks

8.1 Concept and classification of code blocks

A piece 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:
  Ordinary code block
  Construction block
  Static block
  Synchronous code block (more on multi-threading later)

8.2 Common code blocks

Ordinary code block: a code block defined in a method

public class Main{
    public static void main(String[] args) {
        { //直接使用{}定义,普通方法块
            int x = 10 ;
            System.out.println("x1 = " +x);
        } 
        int x = 100 ;
        System.out.println("x2 = " +x);
    }
} 

// 执行结果
x1 = 10
x2 = 100

 This usage is less common

8.3 Constructing code blocks

Construction 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{
    //实例成员变量
    private String name;
    private String gender;
    private int age;
    private double score;
    public Student() {
        System.out.println("I am Student init()!");
    }
     //实例代码块
    {
    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();
    }
}

 // 运行结果
I am instance init()!
I am Student init()!
name: bit age: 12 sex: man

8.4 Static code blocks

A code block defined using static is called a static code block. 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;

    //实例代码块
    {
    this.name = "bit";
    this.age = 12;
    this.gender = "man";
    System.out.println("I am instance init()!");
    }

    // 静态代码块
    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();
    }
}

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 The JVM opens up space and initializes it when loading a class
If a class contains multiple static code blocks, when compiling the code, the compiler will execute (merge) one after another in the defined order
The instance code block will only be executed when the object is created

(Note: The pictures and texts are from the Internet. If there is any infringement, please contact us to delete it!!) 

Hope this helps you guys, thanks for reading! ! !​ 

Guess you like

Origin blog.csdn.net/A1546553960/article/details/134335406