[Java SE] Classes and Objects (Part 1)

Table of contents

1. Preliminary understanding of object-oriented

1.1 What is object-oriented

1.2 Object-oriented and process-oriented

2. Class definition and usage

2.1 Simple understanding of categories

 2.2 Class definition format

3. Instantiation of classes 

3.1 What is instantiation 

3.2 Instantiate objects 

4. this reference (emphasis)

 4.1 Why is there a this reference?

 4.2 Use of this

4.3 Characteristics of this reference

5. Construction and initialization of objects 

5.1 Default initialization

5.2 In-place initialization

Edit

5.3 Construction method (key points)

Summarize:  


This article is the key content in JavaSE. I hope you will take a good look at it.


 1. Preliminary understanding of object-oriented

1.1 What is object-oriented

  • Java is a purely object-oriented language (Object Oriented Program, referred to asOOP. object), in the object-oriented world, everything is
  • 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.

1.2 Object-oriented and process-oriented

Give an example to illustrate the difference between object-oriented and process-oriented:

Process-oriented:

traditional laundry process

The traditional method: the focus is on the process of washing clothes, and it may not work if one link is missing. This isprocess-oriented 

C language is a process-oriented language

 Object-oriented:

Modern laundry process:

The entire process of washing clothes: people put the clothes into the washing machine, pour the washing powder into the washing machine, and start the washing machine. Clothes are always washed

It is divided into four steps in total. The whole process is completed by the interaction of these four objects. You don't need to worry about how it implements the process of washing clothes. It pays more attention to the results.

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

Process it in an object-oriented way, and do not pay attention to the process of washing clothes. Specifically, how the washing machine washes clothes and how to dump them Users don't need to worry about drying. They only need to put the clothes into the washing machine, pour in the washing powder, and turn on the switch. It is completed through the interaction between objects. Note: Process-oriented and object-oriented are not a language, but a method of solving problems. There is no good or bad distinction, both have their own special methods. Application scenarios.


2. Class definition and usage

2.1 Simple understanding of categories

The class is used to describe an entity (object), mainly describing what attributes (appearance size, etc.) the entity (object) has (appearance size, etc.) and what functions (used What to do), after the description is completed, the computer can recognize it.

 For example:

For example: washing machine, which is a brand, can be regarded as a category in Java.
Attributes: product brand, model, product weight, appearance size, color...
Function: washing, drying, timing....

 2.2 Class definition format

When defining a class in java, you need to use the class keyword
 

// 创建类
class ClassName{ 
  field;    // 字段(属性) 或者 成员变量
  method;    // 行为 或者 成员方法
}
  • class is the keyword that defines the class
  • ClassName is the name of the class
  • {} is the main body of the class

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.

For example, we can describe the washing machine just now:

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 washClothes(){  // 洗衣服
    System.out.println("洗衣功能");
 }
 
  public void dryClothes(){   // 脱水
    System.out.println("脱水功能");
 }
 
  public void setTime(){    // 定时
    System.out.println("定时功能");
 }
}

Define another dog class:

class Dog {
    public String name;
    public String color;
    public int age;

    public void eat() {
        System.out.println(name + "吃东西");
    }
    
    public void wag() {
        System.out.println(name + "摇尾巴");
    }
}

Precautions:

  • Note that the class name must be defined in camel case.
  • The writing in front of members is uniformly public.
  • The method written here does not have the static keyword
  • Generally, only one class is defined in a file.
  • The class modified by public must be the same as the file name
  • The class modified by public must be the same as the file name

3. Instantiation of classes 

3.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. ;

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.

3.2 Instantiate objects 

Take the example of a virgin dog as an example:

 

In this way, we create a dog object throughnew , and can instantiate objects to it

Through. You can access the objects inside it through the class object, and you can initialize it

 

Precautions:

  • The new keyword is used to create an instance of an object.
  • Use . to access properties and methods in an object.
  • Two instances of the same class can be created

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. Give an 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 

 Exercises:

1. Can a reference point to a - reference?

Parsing: Cannot. References can only point to objects

All we can say is that dog2 points to the object pointed by dog1

2. Can a reference point to multiple objects at the same time?

Analysis: No, the reference dog1 can only store one object. 

3.Dog1 points to the null object?

Analysis: Error, dog1 does not point to any object 

Realize the exchange of two numbers (key points)

class myValue1 {
    public int val;
}
class myValue2 {
    public int val;
}

public class Test {
    public static void swap(myValue1 val1,myValue2 val2) {
        int tmp = val1.val;
        val1.val = val2.val;;
        val2.val = tmp;
    }
    public static void main(String[] args) {
        myValue1 val1 = new myValue1();
        val1.val = 10;
        myValue2 val2 = new myValue2();
        val2.val = 20;
        System.out.println("交换前");
        System.out.println(val1.val);
        System.out.println(val2.val);
        swap(val1,val2);
        System.out.println("交换后");
        System.out.println(val1.val);
        System.out.println(val2.val);
  }
}

  

Note that basic types must not be exchanged. The objects in them must be accessed through references and their objects must be changed from the address.


4. this reference (emphasis)

 4.1 Why is there a this reference?

You will understand by quoting an example:

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

    public void setDate(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) {
        Date date = new Date();
        date.setDate(2023,11,11);
        date.printDate();
    }
}

Here it is printed successfully, but now if I make a little change, an error will occur


 turn out to be:

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

 Let’s take a look at the print results

I just changed the variable name, why can’t it be printed?

Because

Local variables are used here and are not assigned to

Local variables are used first

You can use thisthis method


 4.2 Use of this

 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.

 

 


Even if you write a lot of them, the system can automatically recognize them:

This refers to the object on which the member method is called.


4.3 Characteristics of this reference

  1.  Type of this: Corresponding 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 the "member method", this can only refer to the current object and cannot refer to other objects.
  4.  This is the first hidden parameter of the "member method". 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 will be responsible for receiving it.

5. Object construction and initialization 

5.1 Default initialization

Why do local variables have to be initialized when used, but member variables do not need to be?

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: after the object space is applied for, the members contained in the object have already set their initial values

 

 So they all have default values

5.2 In-place initialization

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


5.3 Construction method (key points)

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.

 

The constructor method is called when instantiating the object.

Methods that have not been constructed before will also be executed, but without any parameters.

There must be at least one constructor, and Java will come with one without any parameters.


The name is the same but the parameter list is different, thus constituting method overloading. 

Here you can initialize the member variables


If only one constructor is written:

If you create a constructor with parameters, but call a constructor without parameters, an error will be reported, because you must use the constructor you created. If you do not write a constructor, you can write a constructor without parameters.​ 

 Here is a quick way to write constructors without having to enter them one by one:

Or directly use the shortcut keysalt+insert to create as many as you want

Summarize:  

Updated tomorrow [Java SE] package

If there are any deficiencies, please feel free to supplement and communicate.

Friends who see this, please support the blogger and have a free three-in-one, thank you!!!

Guess you like

Origin blog.csdn.net/chaodddddd/article/details/134340019