The latest Java basic series of courses--Day06-classes and objects

Author Homepage: Programming Compass

About the author: High-quality creator in the Java field, CSDN blog expert
, CSDN content partner, invited author of Nuggets, Alibaba Cloud blog expert, 51CTO invited author, many years of architect design experience, resident lecturer of Tencent classroom

Main content: Java project, Python project, front-end project, artificial intelligence and big data, resume template, learning materials, interview question bank, technical mutual assistance

Favorites, likes, don't get lost, it's good to follow the author

Get the source code at the end of the article

​# day04 - Classes and Objects

Dear students, congratulations! ! ! After you have completed the previous courses, it means that you have mastered the basic grammar of Java.

Next, what we are going to learn is the core course in Java- object-oriented programming .

1. Getting Started with Object Orientation

Dear students, why is it said that object-oriented is the core course of Java? Because there are routines for writing Java programs, and object-oriented is the routine for writing Java programs; if you don't know object-oriented programming, then you have learned the Java language for nothing.

So what is going on with this programming routine? Next, let's take a quick look at a case.

Now suppose we need to deal with the three data of the student's name, Chinese score, and math score, and ask to print out the student's total score and average score.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-7U6xSjhd-1689819787582)(assets/1662209848898.png)]

When encountering such a requirement, we used to define methods to do it, as shown in the following figure

Note: Each method here has three parameters

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-5Tlc8oi2-1689819787584)(assets/1662209886046.png)]

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-SVJhv793-1689819787585)(assets/1662209899008.png)]

After defining the method, when we call the method, we need to pass three actual parameters to each method

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-vrf0g0YC-1689819787586)(assets/1662210110729.png)]

In the above case, this programming method is a procedure-oriented programming method. The so-called process-oriented is to write a method, and if there is data to be processed, it is handed over to the method for processing.

But in fact, the three data of name, Chinese score, and math score can be put together and combined into an object , and then let the object provide methods to process its own data. This approach is called object-oriented programming.

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-lArUyEjC-1689819787587)(assets/1662210587156.png)]

To sum up: the so-called object programming is to hand over the data to be processed to the object and let the object handle it.

Second, a deep understanding of object-oriented

Good students, in the last class we have used object-oriented programming routines to process student data. Next, we have to figure out the core issues of object-oriented.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-tl7xiwh1-1689819787588)(assets/1662211382446.png)]

If we understand these three questions, then your understanding of object-oriented is in place.

2.1 What are the benefits of object-oriented programming?

Let's look at the first question first, what are the benefits of object-oriented programming? Then I have to talk about Java's patriarch's understanding of the world.

The patriarch of Java, James Gosling, believes that everything in this world is an object! **Any object can contain some data, and which object the data belongs to will be processed by that object.

In this case, as long as we find the object, we actually find the way to process the data.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Hjo7kNvS-1689819787589)(assets/1662211620054.png)]

So the benefits of object-oriented programming can be summed up in one sentence: object-oriented development is more in line with human thinking habits, making programming easier and more intuitive.

2.2 What exactly is an object in a program?

After talking about the benefits of object-oriented programming, some students here may have questions. In the example you just gave, "car", "mobile phone", and "Cai Xukun" are real things. You can understand it as an object. So what exactly is the object in our program?

Objects are essentially a special kind of data structure . How to understand this structure?

You can understand an object as a table, and the data recorded in the table is the data owned by the object.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-EZERhU2w-1689819787590)(assets/1662212402342.png)]

This is what an object in a program is! To sum it up in one sentence, an object is actually a data table, and whatever data is recorded in the table, the object processes that data.

2.3 How did the object come out?

Just now we mentioned that an object is a data table, so how did this data table come from? This table will not exist for no reason, because Java does not know what data your object will handle, so this table needs to be designed by us.

What is used to design this table? It is a class. A class can be understood as a design diagram of an object or a template of an object.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-SpRHcwgO-1689819787591)(assets/1662213156309.png)]

We need to create an object according to the blueprint of the object. What data is specified in the design diagram, only what data can be contained in the object.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Oxb36LDy-1689819787592)(assets/1662213268590.png)]

One sentence summary: An object can be understood as a data table, and what data can be contained in a data table is designed by class.

3. The principle of object execution in the computer

Dear students, we have already led our students to write object-oriented code, and we also know what is going on with objects. If we figure out how objects are executed in computers, then our understanding of object-oriented will be more professional.

According to the implementation principle of the array we mentioned earlier, the array variable records the address of the real number array in the heap memory. In fact, the principle of object-oriented code execution is very similar to that of arrays.

In fact, Student s1 = new Student();the principle in this sentence is as follows

  • Student s1It means that in the stack memory, a variable of type Student is created, and the variable name is s1

  • Instead, new Student()an object will be created in the heap memory, and the object contains the student's attribute name and attribute value

    At the same time, the system will assign an address value 0x4f3f5b24 to the Student object

  • Then assign the address of the object to the variable s1 in the stack memory, and the object can be found through the address recorded in s1

  • When executing s1.name=“播妞”, it actually finds the address of the object through s1, then finds the name attribute of the object through the object, and then assigns a value to the name attribute of the object 播妞;

After understanding Student s1 = new Student();the principle, Student s2 = new Student();the principle is exactly the same, except that an object is recreated in the heap memory and has a new address. s2.nameIs to access the properties of another object.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-RCwlakKC-1689819787593)(assets/1662213744520.png)]

Fourth, the creation and use of classes and objects

4.1 Class Definition

Defining a class (declaring a class) is actually defining the static properties and dynamic properties (methods) of the class. The user defines a class is actually defining a new abstract data type. Before using the class, it must be defined first, and then the defined class can be used to declare the corresponding variables and create objects.

The basic syntax structure for defining a class:

[类修饰符] class 类名称
       {  //声明成员变量
           [修饰符] 数据类型   变量名;
           //声明成员方法
           [修饰符] 返回值类型 方法名(参数表){…}                
       }

The role of class modifiers:

 1、公共类修饰符 public : Java 语言中类的可访问控制符只有一个: public 即公共的。每个 Java 程序的主类都必须是 public 类作为公共工具。供其它类和程序使用的应定义为 public 类。

 2 、抽象类修饰符 abstract :凡是用 abstract 修饰符修饰的类,被称为抽象类。所谓抽象类是指这种类没有具体对象的一种概念类。这样的类就是 Java 语言的 abstract 类。

 3、最终类修饰符 final :当一个类不可能有子类时可用修饰符 final 把它说明为最终类。被定义为 final 的类通常是一些有固定作用、用来完成某种标准功能的类。

 4、类缺省访问控制符:如果一个类没有访问控制符,说明它具有缺省的访问控制符特性。此时,这个类只能被同一个包中的类访问或引用。这一访问特性又称为包访问性。

The role of member modifiers:

  1、公共访问控制符 public :用 public 修饰的域称为公共域。如果公共域属于一个公共类,则可以被所有其它类所引用。由于 public 修饰符会降低运行的安全性和数据的封装性,所以一般应减少 public 域的使用。

  2、私有访问控制符 private : 用 private 修饰的成员变量 ( 域 ) 只能被该类自身所访问,而不能被任何其它类 ( 包括子类 ) 所引用。

  3、保护访问控制符 protected :用 protected 修饰的成员变量可以被三种类所引用:①该类自身;②与它在同一个包中的其它类;③在其它包中的该类的子类。使用修饰符 protected 的主要作用是允许其它包中它的子类来访问父类的特定属性。

  4、私有保护访问控制符 private protected :用修饰符 private protected 修饰的成员变量可以被该类本身或该类的子类两种类访问和引用。

  5、静态域修饰符 static :用 static修饰的成员变量仅属于类的变量,而不属于任何一个具体的对象,静态成员变量的值是保存在类的内存区域的公共存储单元,而不是保存在某一个对象的内存区间。任何一个类的对象访问它时取到的都是相同的数据;任何一个类的对象修改它时 , 也都是对同一个内存单元进行操作。

   6、最终域修饰符 final :最终域修饰符 final 是用来定义符号常量的。一个类的域 ( 成员变量 ) 如果被修饰符 final 说明,则它的取值在程序的整个执行过程中都是不变的。

   7、易失 ( 共享 ) 域修饰符 volatile :易失 ( 共享 ) 域修饰符 volatile是用来说明这个成员变量可能被几个线程所控制和修改。也就是说在程序运行过程中,这个成员变量有可能被其它的程序影响或改变它的取值。因此,在使用中要注意这种成员变量取值的变化。通常 volatile 用来修饰接受外部输入的域。

   8、暂时性域修饰符 transient :暂时性域修饰符 transient 用来定义一个暂时性变量。其特点是:用修饰符transient 限定的暂时性变量,将指定 Java虚拟机认定该暂时性变量不属于永久状态,以实现不同对象的存档功能。否则,类中所有变量都是对象的永久状态的一部分,存储对象时必须同时保存这些变量。

A member variable of a class describes the internal information of the class. A member variable can be a simple variable or other structured data such as an object or an array. The format of member variables is as follows:

  [修饰符] 变量类型  **变量名** [=初值];

The method of the class is used to define the operation of the member variables of the class. It is a mechanism to realize the internal functions of the class, and it is also an important window for the class to interact with the outside world. The syntax for declaring a method is as follows:

 [修饰符] 返回值的数据类型 方法名(参数列表)
{

  语句序列;

  return [表达式];
}

Example class definition:

class Cylinder   //定义圆柱体类Cylinder
{
    
    
    double radius;     //声明成员变量radius
    int height;        //声明成员变量height
    double pi=3.14;   //声明数据成员pi并赋初值
    void area( ) {
    
      //定义成员方法area(),用来计算底面积
      System.out.println("圆柱底面积="+ pi*radius* radius);
     }
     void volume( ) {
    
      //定义成员方法volume (),用来计算体积
        System.out.println("圆柱体体积="+((pi*radius* radius)*height);
     }
}

4.2 Object Creation

可以将对象理解为一种新型的变量。
对象之间靠互相传递消息而相互作用,消息传递的结果是启动方法,完成一些行为或者修改接受消息的对象的属性。
对象完成工作后,将被销毁,所占用的资源将被系统回收。
一个对象的生命周期:创建 -> 使用 -> 销毁

Steps to create an object
1. Declare a variable pointing to the "object created by the class";
2. Use new to create a new object and assign it to the previously declared variable.
Example: To create an object of the cylinder class Cylinder, the following syntax can be used to create:

   Cylinder  volu;         //声明指向对象的变量volu
   volu = new Cylinder();   //利用new创建新的对象,并让变volu指向它

The format for referencing an object member through an object is as follows:

对象名.对象成员
如, volu.radius = 2.8;    
    volu.height = 5;

If you are referring to a member method, you only need to provide the required parameters in the parentheses of the member method name. If the method does not require parameters, use empty parentheses.

如:volu.area()

*Multiple objects of a class, their member variables are allocated in different memory, so when modifying the member variables of a certain object, others will not be affected.

4.3 Transfer of method parameters

Class methods can have both return values ​​and parameters.
1. Call a method with a variable as a parameter

When calling a method and passing parameters, the parameters are actually the arguments of the method, so the parameters should be passed within the parentheses of the method. Parameters in parentheses can be numeric, string, or even object. Method parameters are local variables.
If the parameter passed in from the outside is assigned to the member variable of the class through the method call, and the formal parameter of the method has the same name as the member variable of the class, you need to use this to identify the member variable.

Class Cylinder
{
    
    
   double radius;

   void SetCylinder(double radius)
    {
    
    
        this.radius = radius;    
    }
  
}

2. Method calls with arrays as parameters or return values

Passing an array: indicates that the parameter is an array, and the actual parameter only gives the array name.
A method whose return value is an array type. If a one-dimensional integer array is returned, add int[] before the method.
When the parameter is a basic data type, it is called by value; when the parameter is a reference variable, it is called by reference.

Class Cylinder
{
   int[] scores;

   void setScores(int[] scores)
    {
        this.scores = scores;    
    }
  
}

3. Variable parameters

A method that receives an unfixed number of parameters is called a variable parameter. The syntax for a method that receives variable parameters is as follows:

返回值类型 方法名(固定参数列表,数据类型…可变参数名)  // ... 为可变参数
     {
        方法体
     }

4.4 Attentions

I have listed these precautions below. Let's explain a few that are difficult to understand (mark the box), and everyone else can understand it at a glance.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-VXpkyPFu-1689819787594)(assets/1662213891968.png)]

Rule 1 : Multiple classes can be written in a code file, but only one can be public modified, and the public modified class must be the same as the file name.

Assuming the file name Demo1.javais assumed to be two classes in this file Demo1类和Student类, the code is as follows

//public修饰的类Demo1,和文件名Demo1相同
public class Demo1{
    
    
    
}

class Student{
    
    
    
}

**The second article:** The data between objects will not affect each other, but multiple variables pointing to the same object will affect each other.

As shown in the figure below, the two variables s1 and s2 respectively record the address values ​​of the two objects, and modify their respective attribute values ​​independently of each other.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-tJFoNstr-1689819787595)(assets/1662214650611.png)]

As shown in the figure below, the two variables s1 and s2 record the address value of the same object, s1 modifies the attribute value of the object, and then accesses this attribute with s2, and you will find that it has been modified.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-G77TvoNQ-1689819787596)(assets/1662215061486.png)]

Five, this keyword

Dear students, next we will learn a few object-oriented knowledge points. Here we first understand what the keyword this means, and then talk about the application scenarios of this.

what is this?

this is a variable that can be used in a method to get the object of the current class.

Let's look at the code shown in the figure below, and use the code to understand what this sentence means. Which object calls this in the method method is which object

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-r7TUu1nP-1689819787597)(assets/1662301823320.png)]

The result of running the above code is as follows

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-cJs2dvWc-1689819787598)(assets/1662302089326.png)]

What is the use of this?

The member variables of this class object can be accessed in the method through this. Let's look at the code in the figure below and analyze the print result
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Zl5ymzJD-1689819787600)(assets/1662303676092.png)]

Analyzing the above code s3.score=325, when the method printPass method is called, the value in the method this.scoreis also 325; while the parameter score in the method receives 250. The execution result is

insert image description here

We have learned about the this keyword here, and remember this sentence: Which object calls this in the method method is which object

6. Constructor

Good students, next we will learn a very practical grammar knowledge - called constructor.

Regarding the constructor, we only need to master the following questions:

  1. What is a constructor?
  2. Master the characteristics of the constructor?
  3. What is the application scenario of the constructor?
  4. What are the precautions for constructors?

Let's learn question by question. Let's first learn what is a constructor?

  • What is a constructor?

    The constructor is actually a special method, but this method has no return value type, and the method name must be the same as the class name.

    As shown in the figure below: there is a Student class below, and the name of the constructor must also be named Student; there are also constructors with empty parameters, and constructors with parameters.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-xRl9AOn7-1689819787602)(assets/1662304435504.png)]

After getting to know the constructor, let's take a look at the characteristics of the constructor.

  • The characteristics of the constructor?

    When an object is created, the constructor is called.

    That is to say new Student(), the constructor is being executed. When the constructor is executed, it means that the object is created successfully.

    [External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-jB50rifJ-1689819787605)(assets/1662304779863.png)]

    When new Student("播仔",99)the object is created, it is executing the constructor with parameters. When the constructor with parameters is executed, it means that the object is created.

    [External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-5Qd1sPzR-1689819787607)(assets/1662304859276.png)]

Regarding the characteristics of the constructor, we remember a sentence: the new object is executing the construction method

  • What is the application scenario of the constructor?

    In fact, constructors are used to create objects. You can do some initialization operations on the properties of the object when creating the object. As shown below:

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-2xFoTmdR-1689819787609)(assets/1662305406056.png)]

  • Constructor considerations?

    After studying the application scenarios of the constructor, let's take a look at the precautions of the constructor.

    1.在设计一个类时,如果不写构造器,Java会自动生成一个无参数构造器。
    2.一定定义了有参数构造器,Java就不再提供空参数构造器,此时建议自己加一个无参数构造器。
    

Let's summarize these questions about constructors. After mastering these questions, the construction method is fully understood.

1.什么是构造器?
	答:构造器其实是一种特殊的方法,但是这个方法没有返回值类型,方法名必须和类名相			同。
	
2.构造器什么时候执行?
	答:new 对象就是在执行构造方法;

3.构造方法的应用场景是什么?
	答:在创建对象时,可以用构造方法给成员变量赋值

4.构造方法有哪些注意事项?
	1)在设计一个类时,如果不写构造器,Java会自动生成一个无参数构造器。
	2)一定定义了有参数构造器,Java就不再提供空参数构造器,此时建议自己加一个无参数构		造器。

7. Encapsulation

Object Oriented Basic Features

封装性:利用抽象数据类型将数据和基于数据的操作封装在一起,保护数据并隐蔽具体的细节,只保留有限的接口与外界联系。

继承性:使特殊类(子类)的对象拥有一般类 (父类)的全部属性与方法,同时可以增添自身的属性和方法。

多态性:一个程序中同名的多个不同方法共存的情况。常用重载和覆盖。

Dear students, next we will learn a very important feature of object-oriented called encapsulation.

1. What is encapsulation?

The so-called encapsulation means that when using a class design object to process the data of a certain thing, the data to be processed and the method of processing the data should be designed into an object.

For example: when designing the student class, the three attributes of the student object's name, Chinese score, and math score, as well as the method of calculating the student's total score and average score, are all encapsulated in the student object.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-038M3qiH-1689819787611)(assets/1662305928023.png)]

Now we know what encapsulation is. Then we learn encapsulation, what do we learn? In fact, in actual development, there are some design specifications when using classes to design the data processed by the object and the method of data processing.

The packaging design specification can be summed up in 8 words: reasonable concealment and reasonable exposure

For example, when designing a car, some parts such as the engine and gearbox of the car do not need to be known to every driver, so they are hidden inside the car.

It is actually safer to hide the engine, gearbox and other parts, because not everyone knows the engine and gearbox very well, and if they are exposed to the outside, they may be damaged by people who do not understand.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-a0N6lJcj-1689819787612)(assets/1662306602412.png)]

When designing a car, in addition to hiding some parts, it is still necessary to expose some things reasonably so that the driver can control the car and let the car run. For example: the ignition button, the steering wheel, the brakes, the accelerator, the gear knob... These are deliberately exposed to allow the driver to control the car.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-P3j6g9Aj-1689819787631)(assets/1662306879230.png)]

Well, by now we have understood some specifications of what is encapsulation. That is: reasonable exposure, reasonable concealment

2. Encapsulated in the code embodiment

After knowing what encapsulation is, how is encapsulation reflected in the code? Generally, when we design a class, we will hide the member variables, and then expose the method of manipulating the member variables.

Here you need to use a modifier called private, the variable or method modified by private can only be accessed in this class.

As shown in the figure below, private double score;it is equivalent to encapsulating the score variable inside the Student object and not exposing it to the outside. If you want to access the score variable in other classes, you cannot directly access it;

If you want to assign a value to the score attribute of the Student object, you have to call the method exposed to the outside world setScore(int score). In this method, you can control the data passed by the caller, which is more secure.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-idMJDjau-1689819787634)(assets/1662335204398.png)]

When you want to get the value of the socre variable, you have to call another method exposed to the outside worldgetScore()

We have learned about encapsulation here.

8. Entity JavaBean

Next, we learn a class that is often written in object-oriented programming - called the entity JavaBean class. Let's first look at what is an entity class?

1. What is an entity class?

An entity class is a special class that needs to meet the following requirements:

insert image description here

Next, we write a Student entity class as required;

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-5DCIc0XF-1689819787636)(assets/1662335451401.png)]

After writing the entity class, let's take a look at its characteristics? In fact, we will find that there are no other methods provided in the entity class except for the methods of storing and fetching values ​​for objects. So the entity class is only used to encapsulate data.

After knowing the characteristics of the entity class, let's take a look at what application scenarios it has?

2. Application scenarios of entity classes

In actual development, the entity class is only used to encapsulate data, and the processing of data is handed over to other classes to complete the separation of data and data business processing. As shown below

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-KxFchPj1-1689819787637)(assets/1662336287570.png)]

In practice, a class is used as a data type. As shown in the figure below, in the StudentOperator class, define a member variable student of the Student type, and then use the constructor to assign values ​​to the student member variable.

Then in the printPass() method of Student, use the student to call the method of the Student object to process the data of the Student object.

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-7cu3BsBz-1689819787639)(assets/1662337507608.png)]

So far, we have learned what the JavaBean entity class is and its application scenarios. Let’s summarize

1.JavaBean实体类是什么?有啥特点
	JavaBean实体类,是一种特殊的;它需要私有化成员变量,有空参数构造方法、同时提供		getXxx和setXxx方法;
	
	JavaBean实体类仅仅只用来封装数据,只提供对数据进行存和取的方法
 
2.JavaBean的应用场景?
	JavaBean实体类,只负责封装数据,而把数据处理的操作放在其他类中,以实现数据和数		据处理相分离。

Nine, the difference between member variables and local variables

Dear students, we have finished learning the basic content of object-oriented. When students are in object-oriented code, they often confuse member variables with local variables. So now let's talk about their differences.
[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-I1s40T8f-1689819787643)(assets/1662353340190.png)]

As shown in the figure below, member variables are outside the method in the class, while local variables are in the method.

insert image description here


At this point, we have finished learning the basics of object-oriented. The core point of object-oriented is encapsulation, which encapsulates data and data processing methods into objects; as for what data should be encapsulated by objects? How to process the data? It needs to be designed by class.

It should be noted that different people may design the same object, the data encapsulated by the object, and the methods provided by the object may be different; as long as the requirements can be fulfilled and the design specifications are met, it is a reasonable design.

10. Use of anonymous objects

So when an object is created, when calling the object's method, you can also directly call the object's method without defining the object's reference variable (that is, without a variable name). Such an object is called an anonymous object.

Example:

将
      Cylinder volu=new Cylinder();
      volu.SetCylinder(2.5, 5,3.14);
改写为:
      new Cylinder().SetCylinder(2.5, 5,3.14);
则Cylinder()就是匿名对象。

There are usually two situations in which anonymous objects can be used:
If only one method call is required for an object.
Pass an anonymous object as an argument to a method call.
Example:

一个程序中有一个getSomeOne()方法要接收一个MyClass类对象作为参数,方法的定义如下:
    public static void getSomeOne (MyClass c)
    {
        ……
     }

You can call this method with the following statement.

 getSomeOne(new MyClass( ) );  //此时的参数就是匿名对象

Eleven, object-oriented comprehensive case

After learning object-oriented grammar knowledge. Next, we make an object-oriented comprehensive case - imitating the movie information system.

The requirements are shown in the figure below

1. 想要展示系统中全部的电影信息(每部电影:编号、名称、价格)

  	2. 允许用户根据电影的编号(id),查询出某个电影的详细信息。

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-UXpURphW-1689819787645)(assets/1662351774659.png)]

When running the program, it can perform different functions according to the user's choice, as shown in the figure below

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-cFZcxLOM-1689819787646)(assets/1662351990387.png)]

Follow the steps below to complete the requirements

1. The first step: define the movie class

First of all, each movie contains relevant information about the movie, such as: movie number (id), movie name (name), movie price (price), movie score (score), movie director (director), movie starring (actor), movie introduction (info).

In order to describe each movie and what information it has, we can design a movie class (Movie). The movie class is only to encapsulate the information of the movie, so it can be written according to the standard JavaBean class.

public class Movie {
    
    
    private int id;
    private String name;
    private double price;
    private double score;
    private String director;
    private String actor;
    private String info;

    public Movie() {
    
    
    }

    public Movie(int id, String name, double price, double score, String director, String actor, String info) {
    
    
        this.id = id;
        this.name = name;
        this.price = price;
        this.score = score;
        this.director = director;
        this.actor = actor;
        this.info = info;
    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public double getPrice() {
    
    
        return price;
    }

    public void setPrice(double price) {
    
    
        this.price = price;
    }

    public double getScore() {
    
    
        return score;
    }

    public void setScore(double score) {
    
    
        this.score = score;
    }

    public String getDirector() {
    
    
        return director;
    }

    public void setDirector(String director) {
    
    
        this.director = director;
    }

    public String getActor() {
    
    
        return actor;
    }

    public void setActor(String actor) {
    
    
        this.actor = actor;
    }

    public String getInfo() {
    
    
        return info;
    }

    public void setInfo(String info) {
    
    
        this.info = info;
    }
}

2. The second step: define the movie operation class

The Movie class we defined earlier is only used to encapsulate the information of each movie. In order to separate movie data and movie data operations, we have to have a movie operation class (MovieOperator).

Because there are multiple movies in the system, the MovieOperator in the movie operation class needs to have one Movie[] movies;to store multiple movie objects;

At the same time, in the MovieOperator class, it provides methods for externally providing and operating movie arrays. For example, if printAllMovies()it is used to print all movie information in the array, searchMovieById(int id)the method searches for a movie information according to the id and prints it.

public class MovieOperator {
    
    
    //因为系统中有多部电影,所以电影操作类中,需要有一个Movie的数组
    private Movie[] movies;
    public MovieOperator(Movie[] movies){
    
    
        this.movies = movies;
    }

    /** 1、展示系统全部电影信息 movies = [m1, m2, m3, ...]*/
    public void printAllMovies(){
    
    
        System.out.println("-----系统全部电影信息如下:-------");
        for (int i = 0; i < movies.length; i++) {
    
    
            Movie m = movies[i];
            System.out.println("编号:" + m.getId());
            System.out.println("名称:" + m.getName());
            System.out.println("价格:" + m.getPrice());
            System.out.println("------------------------");
        }
    }

    /** 2、根据电影的编号查询出该电影的详细信息并展示 */
    public void searchMovieById(int id){
    
    
        for (int i = 0; i < movies.length; i++) {
    
    
            Movie m = movies[i];
            if(m.getId() == id){
    
    
                System.out.println("该电影详情如下:");
                System.out.println("编号:" + m.getId());
                System.out.println("名称:" + m.getName());
                System.out.println("价格:" + m.getPrice());
                System.out.println("得分:" + m.getScore());
                System.out.println("导演:" + m.getDirector());
                System.out.println("主演:" + m.getActor());
                System.out.println("其他信息:" + m.getInfo());
                return; // 已经找到了电影信息,没有必要再执行了
            }
        }
        System.out.println("没有该电影信息~");
    }
}

3. The third step: define the test class

Finally, we need to prepare all the movie data in the test class and save it in an array. The data for each movie can be encapsulated into an object. Then store the object in an array.

public class Test {
    
    
    public static void main(String[] args) {
    
    
        //创建一个Movie类型的数组
        Movie[] movies = new Movie[4];
        //创建4个电影对象,分别存储到movies数组中
        movies[0] = new Movie(1,"水门桥", 38.9, 9.8, "徐克", "吴京","12万人想看");
        movies[1] = new Movie(2, "出拳吧", 39, 7.8, "唐晓白", "田雨","3.5万人想看");
        movies[2] = new Movie(3,"月球陨落", 42, 7.9, "罗兰", "贝瑞","17.9万人想看");
        movies[3] = new Movie(4,"一点就到家", 35, 8.7, "许宏宇", "刘昊然","10.8万人想看");
        
    }
}

After preparing the test data, the next step is to operate on the movie data. We have written the function of closing the movie operation first into the MovieOperator class, so next, create a MovieOperator class object and call the method to complete the relevant functions.

Continue to the main method, and then write the following code.

// 4、创建一个电影操作类的对象,接收电影数据,并对其进行业务处理
MovieOperator operator = new MovieOperator(movies);
Scanner sc = new Scanner(System.in);
while (true) {
    
    
    System.out.println("==电影信息系统==");
    System.out.println("1、查询全部电影信息");
    System.out.println("2、根据id查询某个电影的详细信息展示");
    System.out.println("请您输入操作命令:");
    int command = sc.nextInt();
    switch (command) {
    
    
        case 1:
            // 展示全部电影信息
            operator.printAllMovies();
            break;
        case 2:
            // 根据id查询某个电影的详细信息展示
            System.out.println("请您输入查询的电影id:");
            int id = sc.nextInt();
            operator.searchMovieById(id);
            break;
        default:
            System.out.println("您输入的命令有问题~~");
    }
}

At this point, the movie information system is completed. Friends, try to write it yourself! !

Guess you like

Origin blog.csdn.net/whirlwind526/article/details/131824466