On java classes and objects (not spicy, hard)

Write before: As an object-oriented language, we need to understand the basic concepts of what classes are and what objects are.

Summary:

  1. Object-oriented and process-oriented
  2. Definition Forms of Classes and Object Instantiation
  3. this reference
  4. Re-talk about the initialization process of objects

1. Object-oriented and process-oriented

1.1 What is Object Oriented

As two widely used programming languages, Java and c++ both embody the important programming idea of object-oriented, while Java is a pure object-oriented language (Object Oriented Program, or OOP).Maybe the first helloworld we wrote was in a class Class. In an object-oriented world, everything is an object. Object-oriented is the idea of solving problems, which relies mainly on the interaction between objects to complete one thing. It refers to programs with object-oriented thinking, which is more in line with people's cognitive model of things. It is very friendly to the design, expansion and maintenance of large programs.

1.2 Object Oriented versus Process Oriented

(Here's an example of life to illustrate it more authentic and understandable. For example, when we wash clothes, the traditional way is a process-oriented idea: take water - put clothes - put laundry powder - hand rub - change water - hand rub - screw dry - dry. This way emphasizes the overall process and cannot be missing any link. Every link can be seen as yesA function. But the drawback of writing code with this idea is obvious:

  • The amount of powder you put in your laundry and the way you screw it out vary with the way you wash your clothes
  • If you change to bed linen, a large area of modification is required to wash your shoes

Writing code according to the object-oriented idea can be cumbersome for later expansion and maintenance.

(But modern laundry can be thought of as an object-oriented way of thinking. People put their clothes in the washing machine, put laundry powder in it, and start the machine. We don't focus on how the clothes are cleaned. The whole process can be roughly divided into two steps. The first step is to pull out all the objects from this behavior. For example, laundry can be abstracted out of four.Objects: people, washing machine, clothes and laundry. The second step relies on the interaction between objects to finish the laundry.

Object-oriented is like lid pouring, while process-oriented is more like egg-fried rice

p.s.: Object-oriented and process-oriented are not a language, but different ways of thinking and solving problems. They have no advantages and can be applied to different problems and needs.

2. Definition of classes and object instantiation

2.1 First Identity Class

Objects are the core of object-oriented language. Everything in life (objects) is not recognized by computers when we want to use it. Therefore, we need to use programming languages to abstract objects to describe computers. Classes are required. **Classes are abstract descriptions of an entity (object). **Includes its properties and functions.

Definition of class 2.2

The format of classes defined in java is as follows:The modifier class class name syntax is as follows:

public class Student{
    public String name;//Attribute: Used to describe a class, also becomes a member variable of the class
    public String gender;
    public short age;
    public void goClass(){
        System.out.println(name+"attend classes on time");//Behavior: Used to illustrate what a class does and to become a member method of a class
    }
    public void doHomeworrk(){
        System.out.println(name+"finish one's homework");
    }
}

Be careful:

  • Generally, only one class is defined in a file, and the class name is named after the camel.
  • The class in which the main method resides is generally decorated with public
  • The class decorated with public must have the same name as the file. Do not easily modify the name.

Instantiation of Class 2.3

Defining a class defines a new data type, just like the basic type int, double. For example, the student class above is a data type. It can be used to define variables, and classes can be used to define variables (create objects).The process is called instantiation of classes. Instantiate objects with the new keyword in java. Here we use the student class above as an instance to instantiate objects. The code is as follows:

public class test{
    public static void main(String[] args){
        Student a=new Student();
        a.name="jack";
        a.age=18;
        a.goClass();
        a.doHomework();
        
        Student b=new Student();
        b.name="alice";
        b.age=19;
        b.goClass();
        b.doHomework();
    }
}
//Output Results
jack attend classes on time
jack finish one's homework
alice attend classes on time
alice finish one's homework
  • Use **. ** to access object properties and methods
  • Multiple instance objects can be created in the same class

Description of classes and objects

  1. A class is just a model-like thing that is an abstract description of an entity, defining its properties and functions.
  2. A class is a custom data type, and variables defined by the class are called objects. An object is an objectively existing entity.
  3. A class can create multiple objects, each of which takes up a certain amount of physical space to store its member variables, but classes do not take up physical space to store them.
  4. Classes instantiate objects like building a house with architectural design in reality. Classes are like design drawings, which only design what is needed, but there is no physical building. Similarly, classes are just a design, so the instantiated objects can actually store data and occupy physical space.

3.this reference

3.1 Why are there this references?

Here is an example:

public class Date {
 public int year;
 public int month;
 public int day;
 public void setDay(int year, int month, int day){
 year = year;
 month = month;
 day = day;
 }
 public void printDate(){
 System.out.println(year + "/" + month + "/" + day);
 }
     public static void main(String[] args){
         Date a=new Date();//Object defining two date classes
         Date b=new Date();
        //Set member variable value of object
         a.setDay(2021,9,15);
         b.setDay(2021,9,16);
         //Print date contents in objects
         a.printDate();
         b.printDate();
     }
 }
    //Output Results
0/0/0
0/0/0

In the code above, we can find two problems:

  1. The parameter name is the same as the member variable value. In the setday member method in the date class, the formal parameter is three integer variables year, month, day and the member variable name, so how should the member variable be assigned when assigning?
  2. **How does the member method know which object is calling it?**In the above example, we defined two objects a and b, called the print date method respectively, and got the wrong print result, so how does the printdate method identify which object is calling it and assigning the data content of the corresponding object?

To answer both questions, this refers.

3.2 What is this reference

The java compiler adds a hidden reference type parameter to each member method that points to the current object (the object that invokes the member method at runtime)However, all operations are transparent to the user, that is, the user does not need to pass, and the compiler completes them automatically.

We can still use the date class above as an example:

public class Date {
 public int year;
 public int month;
 public int day;
 public void setDay(this int year, int month, int day){
 this.year = year;//You need to add this reference manually here
 this.month = month;
 this.day = day;
 }
 public void printDate(){
 System.out.println(year + "/" + month + "/" + day);
 }

this reference is automatically added by the compiler and generally does not need to be explicitly given by the user when implementing code. this reference is an object that calls the member method.

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-sLhfN8tl-1632236) (C:\UsersyzyDesktopHe.jpg)]

The value referenced by this is the address value in this object a. This object can be accessed through this. So the first question above, when renaming a member variable with a formal participation, can access the object's properties by simply adding this. to the member variable, and the date results can be printed successfully.

3.3this Reference Properties

  1. About the type of this: corresponding to the type reference of the class to which it belongs, which object call is the reference type of the class to which that object belongs. If A is a Date class, this is a Date type reference
  2. this can only be used in non-static member methods.
  3. In non-static member methods, this can only refer to the object that invoked the method, cannot refer to other objects, has the final attribute, and compiles errors if referencing other objects.
  4. This is the first hidden parameter in a member method parameter, which is passed automatically by the compiler. When the method executes, the compiler is responsible for passing a reference to the calling member method object to the member method, this is responsible for receiving it, and we can write this without having to explicitly write it out when writing code (as demonstrated above), but it can also be added as follows:
 public class Date {
 public int year;
 public int month;
 public int day;
 public void setDay(Date this,int year, int month, int day){
 this.year = year;//You need to add this reference manually here
 this.month = month;
 this.day = day;
 }
 public void printDate(Date this){
 System.out.println(this.year + "/" + this.month + "/" + this.day);
 }
 }

Next, let's make a simple statement at the byte code level:

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-cid9n1ZE-1632248) (C:UsersyzyDesktopt1.jpg)]

In addition, this reference cannot be empty and cannot point to an empty reference (compilation is possible, no syntax issues, but exceptions occur when running).

4 Re-talk about the initialization process of objects

4.1 How to initialize objects

We know that when defining a local variable within java, it must be initialized, or the compilation will fail. If it is an object, we can use the example above to initialize it:

public static void main(String[] args){
         Date a=new Date();//Object defining two date classes
         Date b=new Date();
        //Set member variable value of object
         a.setDay(2021,9,15);
}

Assigning a member variable to an object by calling a member method is obviously cumbersome, and we'll see in our previous code that a member variable can still be used if it doesn't have an initial value.

4.2 Construction Method

4.2.1 Concepts

A construction method (constructor) is a special member method with a fixed format. It must have the same name as the class name, cannot write a return value type, is called automatically by the compiler, and is called only once throughout the life cycle of an object. The purpose of a construction method is to initialize member variables of an object and is not responsible for opening up space for the object. Refer to the following code:

public class Date{
    public int year;
    public int day;
    public Date(int y,int d){
        year=y;
        day=d;
        System.out.println("Call succeeded");
    }
    public static void main(String[] args){
        Date a=new Date();
    }
}
//Output Results
 Call succeeded

The return value type of a construction method cannot be written or void.

4.2.2 Construction Method Properties

Construction methods can be overloaded, and users can provide different construction methods for different parameters depending on their needs. The code is as follows:

public class Date{
    public int year;
    public int month;
    public int day;
    //Parameterless construction method
    public Date(){
        System.out.println("test1");
    }
    //Construction of Two Parameters
    public Date(int a,int b){
        System.out.println("test2");
    }
    //Construction of Three Parameters
    public Date(int a,int b,int c){
        System.out.println("test3");
    }
}

These three constructions constitute a method overload that users can invoke according to different parameter requirements when using. If the user does not explicitly define them, the compiler automatically generates a default construct with no parameter type, which can be demonstrated from the byte code level using the jclasslip plug-in:

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-2zPD6lzG-16242) (C:UsersyzyDesktopt2.jpg)]

We can see that there is an extra init in the method, we have not defined it, and there is only one hidden parameter, this, in the local variable table of the method. So we know that the compiler will unify the name of the construction method as init, and that the construction method is parameterized so that the compiler will automatically generate when there is no construction method.However, once the user has defined the construction method, the compiler does not regenerate.

In the construction method, this can be used to call other construction methods to simplify the code:

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

Two things to note:

  • this () must be the first statement in the construction method.
  • This () cannot be looped, for example, two construction methods cannot use this with each other.

4.3 Default Initialization

As we mentioned above why member variables do not need to be initialized before they are used, we need to understand some of the implications behind the new keyword:

Date a=new Date();

Although this is a simple statement, there is a lot to do at the JVM level. Here is a brief introduction:

  1. Detects whether the class corresponding to the object is loaded or not.
  2. Allocate memory space for objects.
  3. Handles concurrent security issues (such as multiple threads requesting objects at the same time, to ensure that space does not conflict).
  4. Initialize the allocated space, that is, the member variables contained in the object have their initial values set after the object space has been requested. The following table
data typeDefault value
byte0
char'\u0000'
short0
int0
long0L
booleanfalse
float0.0f
double0.0
referencenull
  1. Set object header information.
  2. Call the construction method.

4.4 In-place initialization

In addition, we can give member variables their initial values when they are declared:

public class Date {
 public int year=1999;
 public int month=1;
 public int day=1;
    public Date(){
        
    }
    public Date(int year,int month){
        
    }
    public void printDate(Date this){
 System.out.println(this.year + "/" + this.month + "/" + this.day);
 }
    public static void main(String[] args){
        Date a=new Date();
        a.printDate();
    }
}
//Output Results
1999/1/1

We can look at this process from the byte code level:

[External chain picture transfer failed, source station may have anti-theft chain mechanism, it is recommended to save the picture and upload it directly (img-OBJoPZz-1632437) (C:UsersyzyDesktopit.jpg)]

When the code is compiled, all statements that initialize member variables are added to the first sentence of each constructor.

Of course, there is a lot more about java classes and objects, but here is only a brief summary of the first part. I will continue to summarize and share with you later. Thank you for your reading and comments.

Author: No door on end
r + "/" + this.month + "/" + this.day);
}
public static void main(String[] args){
Date a=new Date();
a.printDate();
}
}
//Output results
1999/1/1

We can look at this process from the byte code level:

[Outer Chain Picture Transfer in Progress...(img-OBJoPpZz-1632242843357)]

When the code is compiled, all statements that initialize member variables are added to the first sentence of each constructor.

​	Of course java There are many more classes and objects, here is only the first part of the rough summary. I will continue to summarize and share with you later. Thank you for your reading and comments.

>
>
>Author: No door on end

Keywords: Java

Added by flash_78 on Tue, 21 Sep 2021 19:16:51 +0300