[Java | Basics] Classes and Objects

1 Introduction

This article mainly addresses the following three questions

  • class definition and instantiation
  • Construction method
  • this keyword

2. What is object-oriented

As we all know, process-oriented and object-oriented are two important programming ideas, and Java is an object-oriented language. Object-oriented (Object Oriented Programming, referred to as "oop"). Object-oriented has three major characteristics: . These contents will be
detailed 封装 继承和多态later Introduction.
In an object-oriented world, everything is an object. Object is the problem. Object-oriented is an idea to solve problems. It mainly relies on the interaction between objects to complete one thing. Therefore, in Java, we operate on objects one by one. By instantiating objects, calling objects The method realizes the corresponding function. In object-oriented, we don't have to pay attention to how the object realizes the corresponding function.

For example, there is an air conditioner, which can adjust the indoor temperature (heating or cooling), dehumidification and other functions. The air conditioner is an object here. We only need to call the heating and cooling functions of the air conditioner to achieve the results we want.

3. Class definition

A class is used to describe an entity (object).类的定义要使用class关键字

// 语法格式为:
class 类名{
    
    
	// 成员变量
	// 成员方法
}

Take the above-mentioned air conditioner as an example, we need to describe the object of the air conditioner by defining the air conditioner class. The air conditioner has information such as color, size and model, and the air conditioner has functions such as cooling and heating. Define the air conditioner class
:

class AirConditioner{
    
    
	// 成员变量
    String colour; // 颜色
    double size; // 尺寸
    String model; // 型号
	// 成员方法
    void heating(){
    
    
        System.out.println("开启制热功能");
    }
    void refrigeration(){
    
    
        System.out.println("开启制冷功能");
    }
}

When defining a class, the member variables and member methods of the class can be defined according to requirements.下面讲解中的类皆是上述的这个空调类

4. Class instantiation

After defining the class object, how do we use the class? This requires the instantiation of the class. Defining a class is equivalent to defining a new type in the computer. The process of creating an object with a class type is called class Instantiate.使用new关键字进行类的实例化

// 语法
类名 对象名 = new 类名();

For example

    public static void main(String[] args) {
    
    
    	// 类名 对象名 = new 类名(); 
        AirConditioner airConditioner = new AirConditioner();
    }

After instantiating the class object, we can .access the member variables and member methods of the class by adding the object name of the instantiated object.

    public static void main(String[] args) {
    
    
        AirConditioner airConditioner = new AirConditioner();
        System.out.println("颜色: "+ airConditioner.colour);
        System.out.println("尺寸: "+ airConditioner.size);
        System.out.println("型号: "+ airConditioner.model);
        airConditioner.heating();
        airConditioner.refrigeration();
    }
    // 输出结果:
    // 颜色: null
	// 尺寸: 0.0
	// 型号: null
	// 开启制热功能
	// 开启制冷功能

It should be noted here that in the main method, if a variable is defined without initialization, an error will be reported when it is used.
For example:
insert image description here
insert image description here
but the member variables in the class will not have this problem, and the member variables in the class have default values The.
Basic data types:

type of data Defaults
int 0
short 0
long 0
byte 0
float 0.0f
double 0.0
char /u0000
boolean false

Note: The default value for reference data types is null.

Since the member variables of the object can be accessed through the object name of the instance object + ., the member variables of the object can be initialized in this way.
For example:

    public static void main(String[] args) {
    
    
        AirConditioner airConditioner = new AirConditioner();
        airConditioner.colour = "白色";
        System.out.println("颜色: "+ airConditioner.colour);
    }
    // 输出结果:
    // 颜色: 白色

A class can be understood as a "model". The same class can create multiple instance objects.
For example:

    public static void main(String[] args) {
    
    
        AirConditioner airConditioner1 = new AirConditioner();
        AirConditioner airConditioner2 = new AirConditioner();
        AirConditioner airConditioner3 = new AirConditioner();
    }

5. Object construction and initialization

.As mentioned above, we can initialize member variables through the object name of the instance object + method, but if there are many classes and many instance objects, then it will be very troublesome to use this method to initialize member variables at this time. Therefore, Java Provides us with a method called "构造方法" this to help us initialize member variables

Constructor: Also known as a constructor, it is a special member method whose name must be the same as the class name. When an object is created, it is automatically called by the compiler , and it is called only once
in the entire life cycle of the object .

Construction method:

  • The name is the same as the class name, and there is no return value type, even if it is set to void
  • Generally, the public decoration is used
    to be automatically called by the compiler when the object is created, and it is called only once in the life cycle of the object

insert image description here
The above is the default, no-argument construction method. It is also the construction method that the compiler automatically calls when there is no construction method. When
I add an output statement to the construction method:
insert image description here
you can see that I did not call the construction method, but The statement in the construction method is still output. This also verifies that the construction method will be called automatically when the object is instantiated. Therefore, we can pass in parameters and let the construction method initialize the member variables for us.

    public AirConditioner() {
    
    
        System.out.println("执行了 无参 的构造方法");
    }

    public AirConditioner(String a) {
    
    
        colour = a;
        System.out.println("执行了 一个参数 的构造方法");
    }

    public AirConditioner(String a, double b, String c) {
    
    
        colour = a;
        size = b;
        model = c;
        System.out.println("执行了 三个参数 的构造方法");
    }

insert image description here
When talking about methods, I mentioned "重载"this concept.
There are three points to note about method overloading: 1. Method overloading has nothing to do with the return value 2. The parameter list cannot be the same (number, order and type of formal parameters, etc.) 3. Method The name must be the same.
The construction method can also be overloaded. The above three construction methods constitute the overloading of the method.

Using the construction method, we can initialize the member variables. According to the number of actual parameters we pass in, the construction method of the corresponding parameters will be called automatically.
insert image description here

右键 选择Generate
insert image description here
Let's print the contents of the member variables in these classes. You can choose toString() here in IDEA and
insert image description here
IDEA will generate such a method for us.
insert image description here

Next, let's print the good instance object of the instance
insert image description here

6. this reference

In the above code, there is actually a problem, that is, the variable names of the formal parameters in the construction method are written casually. If there are many member variables to be initialized, and they are not written in order (doge), it will be a headache to look at.
insert image description here
At this time, some smart students may say that it is enough to set the name of the formal parameter to be the same as the member variable. Next, let’s try

    public AirConditioner(String colour, double size, String model) {
    
    
        colour = colour;
        size = size;
        model = model;
        System.out.println("执行了 三个参数 的构造方法");
    }

insert image description here
It can be seen that although the constructor is called, it is not initialized. The
main reason for this is that in the constructor, the compiler does not know who assigns the value to whom? Member variable to member variable? Parameter to parameter? Parameters to member variables? Member variable parameters?
insert image description here
In order to solve this problem, Java can provide us with "this"such a keyword

The this reference points to the current object (the object that calls the member method when the member method is running), and all member variable operations in the member method are
accessed through this reference

Modify the above code
insert image description here
insert image description here
At this point, the initialization can be completed correctly.
After using this, it tells the compiler that the front is the member variable of the current class, and the latter is the formal parameter.

Regarding the construction method, we can also use IDEA to help us generate it automatically. Same as toString,
insert image description here
insert image description here
you can select the member variable you want to initialize to generate the corresponding construction method. To select multiple member variables, you can press and hold to CTRLselect.

the characteristics of this

    1. The type of this: the corresponding class type reference, that is, which object is called is the reference type of which object
    1. this can only be used in "member methods"
    1. In the "member method", this can only refer to the current object, and can no longer refer to other objects

Supplement: It can also be initialized in the class

class AirConditioner{
    
    
    String colour = "白色"; // 颜色
    double size; // 尺寸
    String model; // 型号

    public AirConditioner() {
    
    
        System.out.println("执行了 无参 的构造方法");
    }
}

insert image description here
This initialization method is usually used with the "final" keyword, which will be introduced in detail later

7. Summary

The article ends here. Although the content of the article is not difficult, there are still a lot of places that need attention. Classes and objects are the most basic in learning Java, so you must master them

Thank you for watching! I hope this article can help you!
"Java Column" is constantly being updated, welcome to subscribe!
"Wish to encourage you and work together!"
insert image description here

Guess you like

Origin blog.csdn.net/m0_63463510/article/details/129199159