[Java SE] Classes and Objects

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 class

【2.2】Class definition format

【2.3】Practice

【2.3.1】Define a dog class

【2.3.2】Define a student class

【3】Instantiation of class

【3.1】What is instantiation?

【3.2】Description of classes and objects

【4】Reference of this

【4.1】Why should we have this reference?

【4.2】What is this reference?

【4.3】Characteristics of this reference

【5】Construction and initialization of objects

【5.1】How to initialize objects

【5.2】Construction method

【5.2.1】Concept

【5.2.2】Features

【5.3】Default initialization


classes and objects

【1】Preliminary understanding of object-oriented

【1.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.

【1.2】Object-oriented and process-oriented

[Traditional way of washing clothes]

 

        The focus is on the process of washing clothes . If one link is missing, it may not work.

        Moreover, different clothes are washed in different ways, for different lengths of time, and in different wringing methods, which makes them 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 .

[Modern way of washing clothes]

 

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 . Note: 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 scenario.

【2】Class definition and usage

        Object-oriented programming focuses on objects, which are entities in real life, such as washing machines. But the computer does not know the washing machine, and the developer needs to tell the computer what a washing machine is.

 

        The left side of the picture above is a simple description of the washing machine. This process is called abstracting the washing machine object (entity) (re-cognition of a complex thing) . However, these simplified abstract results cannot be recognized by computers. Developers can use a certain An object-oriented programming language is used to describe it, such as Java language.

【2.1】Simple understanding class

        Classes are used to describe an entity (object) , mainly describing what attributes (appearance size, etc.) and functions (what it is used for) the entity (object) has. After the description is completed, the computer can recognize it.

比如:洗衣机,它是一个品牌,在Java中可以将其看成是一个类别。
属性:产品品牌,型号,产品重量,外观尺寸,颜色...
功能:洗衣,烘干、定时....

        In Java language, how to 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 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.

[Example: Define a washing machine class]

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("定时功能");
    }
}

        The washing machine class is defined in the computer using Java language. After javac compilation, a .class file is formed, which can be recognized by the computer based on the JVM.

【Precautions】

  • Note that class names are defined in camel case.

  • The writing method before members is unified as public, which will be explained in detail later.

  • The method written here does not have the static keyword. It will be explained in detail later.

【2.3】Practice

【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

class Student {
    // 学生的属性
    public String name;
    public String gender;
    public short age;
    public double score;
    
    // 狗行为
    public void DoClass(){}
    public void DoHomework(){}
    public void Exam(){}
}

【Precautions】

  1. Generally, only one class is defined in a file.

  2. The class where the main method is located should generally be decorated with public (note: Eclipse will look for the main method in the public-modified class by default).

  3. The class modified by public must be the same as the file name.

  4. Do not modify the name of the public-modified class easily. If you want to modify it, modify it through development tools (demonstrate to classmates).

【3】Instantiation of class

【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. , 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.

 

public class Main{
    public static void main(String[] args) {
        PetDog dogh = new PetDog(); //通过new实例化对象
        dogh.name = "阿黄";
        dogh.color = "黑黄";
        dogh.barks();
        dogh.wag();
        PetDog dogs = new PetDog();
        dogs.name = "阿黄";
        dogs.color = "黑黄";
        dogs.barks();
        dogs.wag();
    }
} 
输出结果:
阿黄: 旺旺旺~~~
阿黄: 摇尾巴~~~
赛虎: 旺旺旺~~~
赛虎: 摇尾巴~~~

【Precautions】

  • The new keyword is used to create an instance of an object.

  • Use . to access properties and methods in an object.

  • Pairs of instances of the same class can be created.

【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 custom type that can be used to define variables.

  3. A class can instantiate multiple objects, and the instantiated objects occupy actual physical space and store class member variables .

  4. Let’s use an analogy. 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】Reference of this

【4.1】Why should we have this reference?

[Look at an example of date class first]

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 date1 = new Date();
        date1.year = 2022;
        date1.month = 12;
        date1.day = 12;
        
        Date date2 = new Date();
        date2.year = 2022;
        date2.month = 11;
        date2.day = 11;
        
        Date date3 = new Date();
        date3.year = 2022;
        date3.month = 10;
        date3.day = 10;
        
        date1.printDate();
        date2.printDate();
        date3.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, I have the following two questions:

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 variable parameters? I guess I can’t even figure it out.

        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 object's data is being printed?

 

Let this quote unveil this mystery.

【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 are transparent 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 setDate(int year, int month, int day) {
        this._year = year;
        this._year = month;
        this._year = day;
    }

    // 成员方法
    public void printDate() {
        System.out.println(_year + "年" + _month + "月" + _day + "日");
    }

    public static void main(String[] args) {
        Date date1 = new Date();
        date1._year = 2022;
        date1._month = 12;
        date1._day = 12;

        Date date2 = new Date();
        date2._year = 2022;
        date2._month = 11;
        date2._day = 11;

        Date date3 = new Date();
        date3._year = 2022;
        date3._month = 10;
        date3._day = 10;

        date1.printDate();
        date2.printDate();
        date3.printDate();
    }
}

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

 

【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 "member methods".

  3. In a "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", 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 will be responsible for receiving it.

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

 

【5】Construction and initialization of objects

【5.1】How to initialize objects

        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.

public static void main(String[] args) {
	int a;
	System.out.println(a);
} 
// Error:(26, 28) java: 可能尚未初始化变量a

        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:

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. Two problems were discovered through the above examples:

  1. It is troublesome to call the SetDate method to set a specific date every 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?

【5.2】Construction method

【5.2.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 .

public class Date {
    // 构造方法:
    // 名字与类名相同,没有返回值类型,设置为void也不行
    // 一般情况下使用public修饰
    // 在创建对象时由编译器自动调用,并且在对象的生命周期内只调用一次
    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 int _year;
    public int _month;
    public int _day;

    /* 入口函数Main */
    public static void main(String[] args) {
        // 此处创建了一个Date类型的对象,并没有显式调用构造方法
        Date date1 = new Date(2022,12,12);  // 输出Date(int,int,int)方法被调用了
        date1.printDate();
    }
}

[Note] The function of the constructor method is to initialize the members in 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 an object is created, and is only called once during the life cycle of the object (equivalent to the birth of a person, each person can only be born once)

  4. The constructor can be overloaded (users provide constructors with different parameters according to their own needs)

public class Date {
    // 无参构造方法
    public Date() {
        System.out.println("我是一个无参的构造方法");
    }
    // 带有三个参数的构造方法
    public Date(int year, int month, int day) {
        System.out.println("我是一个带3个参数的构造方法");
        this._year = year;
        this._month = month;
        this._day = day;
    }

    // 成员方法
    public void printDate() {
        System.out.println(_year + "年" + _month + "月" + _day + "日");
    }

    // 成员属性
    public int _year;
    public int _month;
    public int _day;

    /* 入口函数Main */
    public static void main(String[] args) {
        Date date1 = new Date(2022,12,12);  
        date1.printDate();
    }
}

The above two constructors have the same name but different parameter lists, thus forming method overloading .

  1. If the user does not explicitly define it, the compiler will generate a default constructor, and the generated default constructor must be parameterless.

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();
    }
}

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, 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
    找到: 没有参数
    原因: 实际参数列表和形式参数列表长度不同
 */
  1. 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;
    }
}

【Notice】

  • this(...) must be the first statement in the constructor.

  • Cannot form a ring.

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

/* 无
参构造器调用三个参数的构造器,而三个参数构造器有调用无参的构造器,形成构造器的递归调用
编译报错:Error:(19, 12) java: 递归构造器调用
 */
  1. In most cases, public is used for modification, and private modification is used in special scenarios (you will encounter it when we talk about singleton mode later).

【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 some of what happens behind the new keyword:

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

At the program level, it is just a simple statement. At the JVM level, many things need to be done. 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. To deal with concurrency security issues such as: multiple threads applying 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:

type of data default value
byte 0
char '\u0000'
short 0
int 0
long 0L
boolean false
float 0.0f
double 0.0
reference null

Guess you like

Origin blog.csdn.net/lx473774000/article/details/131928705