Java classes and objects (detailed explanation in 7,000 words!!! Take you to thoroughly understand classes and objects)


Table of contents

1. Preliminary understanding of object-oriented

1. What is object-oriented

2. Object-oriented and process-oriented

(1) Traditional washing process

(2) Modern laundry process

Edit

2. Definition and use of classes

1. Class definition format

3. Instantiation of classes

1. What is instantiation?

2. Class and object description

4. The use of this

1. Why use this

Write a date class

reason:

Solution:

2. What is this reference?

3. Characteristics of this reference

5. Object construction and initialization

1. How to initialize the object

2. Construction method

(1) Concept

(2) Characteristics

3. Default initialization

4. In-place initialization

6. Packaging

1. The concept of packaging

2. Access qualifier

3. Package expansion package

(1) Concept of package

(2) Import classes in the package

(3) Customized package

(4) Examples of package access rights control

(5) Common packages

7. static members

1. Let’s talk about students again

2. Static modification of member variables

3. Static modified member method

4. Initialization of static member variables

8. Code blocks

1. Code block concept and classification

2. Ordinary code blocks

3. Construct code blocks

4. Static code block



1. Preliminary understanding of object-oriented

1. What is object-oriented

Java is a pure object-oriented language (Object Oriented Program, OOP for short). In the object-oriented world, everything is an object. Object-oriented is an idea for solving problems, which mainly relies on the interaction between objects to complete one thing. Using object-oriented thinking to deal with programs is more in line with people's understanding of things, and is very friendly to the design, expansion and maintenance of large programs.
 

2. Object-oriented and process-oriented

(1) Traditional washing process

Traditional laundry focuses on the process of washing clothes. If one link is missing, it may not work. Moreover, different clothes are washed in different ways, length of time, and wringing methods, which makes it more troublesome to deal with. If you are going to wash your shoes in the future, that's another way to put them. Writing code in this way will be more troublesome to expand or maintain in the future.

(2) Modern laundry process

There are four objects in total: people, clothes, laundry, and washing machines

The entire process of washing clothes is to throw the clothes into the washing machine, add the washing clothes, start the washing machine, and the washing machine will complete the washing process and dry the clothes.

The whole process is mainly completed by the interaction of four objects: people, clothes, washing powder, and washing machines. People do not need to care about how the washing machine washes clothes or how to dry them.

Processing in an object-oriented manner does not focus on the process of washing clothes. Users do not need to care about how the washing machine washes clothes and how to dry them. They only need to put the clothes into the washing machine, pour in the washing powder, and turn on the switch. That is, it is done through the interaction between objects.

Notice:

Process-oriented and object-oriented are not a language, but methods of solving problems. They are not good or bad, and each has its own special application scenarios.
 

2. Definition and use of classes

1. Class definition format

class class name {

        Class attributes (member variables);

        Class behavior (member methods);

}

The contents contained in a class are called members of the class. Attributes are mainly used to describe classes and are called member attributes or class member variables of the class. Methods mainly describe what functions a class has and are called member methods of the class.
 

example:

 class WashMachine {

        //属性
        public String brand;//品牌
        public String type;//型号
        public double weight;//重量

        //行为
        public void washClothes() {
        //洗衣服
            System.out.println("洗衣功能");
        }
    }

Please note that the class name is defined in camel case.

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

 

3. Instantiation of classes

1. What is instantiation?

Defining a class is equivalent to defining a new type in the computer, similar to int and double, except that int and double are built-in types that come with the Java language, while the class is a new type defined by the user. , such as the above: 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. In Java, the new keyword is used to instantiate the object with the class name.

example:

class PetDog {
    public String name;//姓名
    public String color;//颜色

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

    public void braks() {
        System.out.println("汪汪汪");
    }

    public void print() {
        System.out.println(this.name);
        System.out.println(this.color);
    }
}
public class TestDemo {
    public static void main(String[] args) {

        PetDog petdog1 = new PetDog();
        PetDog petdog2 = new PetDog();

        petdog1.name = "阿黄";
        petdog1.color = "黄色";
        petdog1.wag();
        petdog1.braks();
        petdog1.print();

        petdog2.name = "阿黑";
        petdog2.color = "黑色";
        petdog2.wag();
        petdog2.braks();
        petdog2.print();
    }
}

Output result:

Note:
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 two instances.
 

2. Class and object description

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 custom type that can be used to define variables.
3. A class can be instantiated For multiple objects, the instantiated objects occupy actual physical space and store class member variables.
4. For example. Instantiating objects from a class is like using architectural design drawings to build a house in reality. A class is like a design drawing. It only designs what is needed, but there is no physical building. Similarly, a class is just a design that is instantiated. Objects can actually store data and occupy physical space.

4. The use of this

1. Why use this

Let’s look at the following examples first:

Write a date class

Output results

If we change the formal parameter name of setDate to be the same as the time member variable, what will the output result become?

It becomes all 0

reason:

When we change the formal parameter name to be the same as the member variable name , the value of the formal parameter name here is different from the value we expect.

One is the actual parameter passed in, and the other is the member variable. However, in the class, we follow the principle of local variables taking precedence . The parameters here represent the member variables. When assigning values ​​below, the formal parameters are assigned to themselves. The int type has no value assigned, and its default value is 0 , so all 0s will be printed.

Solution:

As shown in the picture:

Output result:

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 are transparent to the user, that is, the user does not need to pass it, the compiler automatically completes it.

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

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 "member methods".
3. In "member methods", this can only refer to the current object, not the current object. Then refer to other objects
4. this is the first hidden parameter of the "member method", and the compiler will automatically pass it. When the member method is executed, the compiler will be responsible for passing the reference of the calling member method object to the member method, and this is responsible for to receive


A simple demonstration at the code level --->Note: The Date class on the right side of the picture below can also be compiled.

5. Object construction and initialization

1. How to initialize the object

From the previous knowledge points, we know that when defining a local variable inside a Java method, it must be initialized, otherwise the compilation will fail.

To make the above code compile, it is very simple. Just set an initial value for a before officially using it.

If it is an object:

You need to call the SetDate method written before to set the specific date into the object. Two problems were discovered through the above examples:
1. It is troublesome to call the SetDate method to set a specific date each time the object is created. How should the object be initialized?
2. Local variables must be initialized before they can be used. Why can they still be used without giving a value after the field is declared?
 

2. Construction method

(1) Concept

The constructor method (also called a constructor) is a special member method whose name must be the same as the class name. It is automatically called by the compiler when the object is created, and is called only once during the entire object's life cycle.

(2) Characteristics

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 be overloaded (users provide constructors with different parameters according to their own needs)

5. If the user does not explicitly define it, the compiler will generate a default constructor, and the generated default constructor must have no parameters.

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

Note: Once defined by the user, it is no longer generated by the compiler. (Rescue the emergency, not the poor)

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

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

7. In most cases, public is used for modification, and in special situations, it is modified by private.

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?

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

It is just a simple statement at the program level, but many things need to be done at the JVM level. Here is a brief introduction:
1. Check whether the class corresponding to the object is loaded, and load it if not.
2. Allocate memory space for the object
. 3. Handle concurrency safety. Problem
: 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: after the object space is applied for, 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
 

4. In-place initialization
 

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

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

6. Packaging

1. The concept of packaging

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? To put it simply, it is the shell shielding details .
For example: For a complex device like a computer, all that is provided to the user is: turning on and off, inputting through the keyboard, display, USB jack, etc., allowing the user to interact with the computer and complete daily tasks. But in fact: what the computer really works is the CPU, graphics card, memory and other hardware components

For computer users, they do not need to worry about the internal core components, such as how the circuits on the motherboard are laid out, how the CPU is designed, etc. Users only need to know how to turn on the computer and how to interact with the computer through the keyboard and mouse. Therefore, when computer manufacturers leave the factory, they put a shell on the outside to hide the internal implementation details, and only provide power switches, mouse and keyboard jacks to the outside so that users can interact with the computer.


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.
 

2. Access qualifier

Encapsulation is mainly achieved in Java through classes and access rights: classes can combine data and methods of encapsulating data, which is more in line with human understanding of things, while access rights are used to control whether methods or fields can be used directly outside the class. . There are four access qualifiers provided in Java:

For example:
public: can be understood as a person's appearance characteristics, which can be seen by everyone.
default: it is not a secret for one's own family (in the same package), but it is private for others.
private: only one knows, other people know. Do not know at all


[Explanation]
protected is mainly used in inheritance.
Default permission refers to: the default permission when nothing is written.
Access permissions can not only limit the visibility of members in the class, but also control the visibility of the class.

3. Package expansion package

(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. 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.

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) Import classes in the package

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

However, this way of writing is more troublesome. You can use the import statement to import the package.

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

However, we recommend that you explicitly specify the class name to be imported . Otherwise, conflicts are still prone to occur.

In this case you need to use the full class name

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

Precautions:

There is a big difference between import and C++'s #include. C++ must #include to introduce the contents of other files, but Java does not require it.

import is just to make it more convenient when writing code. import is more similar to C++'s namespace and using

(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.bit.demo1).
③The package name must match the code path. For example, if you create a package of com.bit.demo1, then there will be a corresponding path com/bit/demo1 to store the code. ④If a
class does not have a package statement, the class will be placed in a default package.


Operation steps
① First create a new package in IDEA: right-click src -> New -> Package

②Enter the package name in the pop-up dialog box, for example com.bit.demo1

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

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

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

(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:

(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


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:

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.


Each object will contain a copy of the member variables previously 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.
 

2. Static modification of 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 and are shared by all objects.
 

[Characteristics of static member variables]
① 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. ② It can be
accessed through the object or the class name, but generally It is more recommended to use the class name to access
③ Class variables are stored in the method area
④ The life cycle follows the life of the class (ie: created when the class is loaded and destroyed when the class is unloaded)

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.

3. Static modified member method

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?

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]

① It does not belong to a specific object, it is a class method.
② It can be called through the object or through the class name.static method name (...). It is more recommended to use the latter.
③ You cannot access any non-static method in the static method. Member variables

④ No non-static method can 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.         

⑤Static methods cannot be overridden and cannot be used to implement polymorphism

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.
 

①In-place initialization: In-place initialization refers to: giving the initial value directly when defining

②Static code block initialization (continue to see later)

8. Code blocks

1. Code block concept and classification

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 (not discussed here)

2. Ordinary code blocks

This usage is less common
 

3. Construct code blocks

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.

4. Static code block

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

Notes
① No matter how many objects are generated by a static code block, it 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 code, the compiler will execute (merge) one after another in the defined order.
④The instance code block will only be executed when an object is created.
 

Guess you like

Origin blog.csdn.net/cool_tao6/article/details/132779013