Current location - Plastic Surgery and Aesthetics Network - Plastic surgery and medical aesthetics - How to understand object-oriented programming
How to understand object-oriented programming
[quote] 1. Basic concepts:

On the Class and Object of 1. 1

If you ask me, whether it is a process-oriented language or an object-oriented language, the first thing I want to tell him is classes and objects! -"What is the world made of?" If different people answer this question, they will get different answers. If you are a chemist, he may tell you, "You don't have to ask. The world is made up of molecules, atoms, ions, etc. " What if it is a painter? He may tell you, "The world is made up of different colors". ..... Ha ha, opinions vary! But it would be much more interesting if taxonomists thought about it. He will tell you that "the world is made up of different kinds of things and things". As object-oriented programmers, we should consider the problem from the perspective of taxonomists! Yes, the world is made up of animals, plants and so on. Animals are divided into unicellular animals, multicellular animals, mammals and so on, and mammals are divided into humans, elephants, tigers, and so on!

Now, from an abstract point of view, let's define "class"! I mean, from an abstract point of view, you answer me, "What is a person?" First of all, let's look at some characteristics of human beings, including attributes (some parameters, values) and methods (some behaviors, what he can do! )。 Everyone has some attributes such as height, weight, age, blood type and so on. People can work, people can walk upright, people can use their brains to create tools and so on! People are different from other types of animals, because everyone has the attributes and methods of being a group. "Man" is just an abstract concept, it is just a concept, it is a non-existent entity! But all objects with the attributes and methods of "people" are called people! This object "person" is a real entity! Everyone is the object of this group. Why is a tiger not a person? Because it has no human attributes and methods, tigers can't walk upright, can't use tools and so on! So tigers are not people!

Therefore, a class describes a group of objects with the same characteristics (attributes) and behaviors (methods). In a program, a class is actually a data type! For example: integers, decimals and so on. Integers also have a set of characteristics and behaviors. The difference between process-oriented language and object-oriented language is that process-oriented language does not allow programmers to define their own data types, but can only use the data types built into the program! In order to simulate the real world and solve problems better, we often need to create data types necessary to solve problems! Object-oriented programming provides us with a solution.

1.2 built-in data types and functions:

When store data, that three basic attributes that a compute program must track are:

1. Where is the information stored?

2. What is the stored value;

3. What kind of information is stored?

Let's look at the built-in data types of programming languages! (Ha ha, it's hard to say, because each language has its own unique data type, but this is a minority after all. For example, there are byte data in JAVA, but not in C++. I hope everyone can draw inferences! ) such as integer "int" and floating-point data "float"! The String "string", as well as arrays and structures, etc. However, when writing a program, we will create a type of variable or constant as needed. For example, because we need to create an integer variable int i = 5, we can do this. And I will probably change the value of I as needed, that is, I will give it a new value, such as making it equal to 6, so that I can be changed to I = 6; where necessary; From this we know that the quantity that can change in value is called variable. The quantity that will not change is called a constant, which is declared with the count keyword in C++ and the final keyword in JAVA. Because the sentence formats of different languages are different, I won't introduce them here. Please refer to related books for details!

This paper mainly discusses functions. We can think of a function as a "black box" to achieve a certain function-this function is set by you. For example, now I ask you "How much is 2+3"? I'm sure you can answer quickly that I'm equal to 5. Let's analyze what information this sentence contains! First of all, I want to imagine your brain as a black box. I don't know or need to know how your brain works (that is, how to calculate). What I care about is what information I send you. What did you do with this information? What message did you give me back? Need to remind you that each method will return a message to the caller, except the constructor (I will introduce it in detail later). I need to think of myself as a programmer now. What about you? Computers, of course! No one is smart in computing, it will only run in a specific format agreed in advance. I want it to have the above functions, then I have to define this black box first! First of all, I want to tell you that this black box will have two integer values (this is the so-called parameter, which is the information that programmers need to give to the black box), and then I want to define the black box to add these two integers (this is the processing of data by the black box, and you can do whatever you need). )。 Finally, mark it and return it to me with integer value (this is the information returned by the black box to the programmer). This defines a function. Let's look at the writing format:

int addnum(int x,int y){

Returns x+y;

}

The specific meaning is this:

Int /* return value type */ addnum /* method (black box) name */ (int x, int y/* parameter passed in */) {

Returns x+y; /* Internally, I want to find a way to return the result to the caller */

}

First of all, please pay attention to the "return" statement above! The return keyword means to return the following information to the caller! Just like above, because I ask you, you answer me. I don't ask you, and you don't have to answer me! The same is true in computers. Where is this function called? I can only tell you to call it where you need it! Of course, you can change the parameters, return values and internal implementation as needed, and you have to refer to relevant materials for how to define how to call! I'm just here to give you an idea!

Sometimes you will encounter such a problem. I want you to remember that my age is 20! Literally, you didn't return my message! In fact, however, you did send me a message, the content of which was "no information, that is, no return value type void". The specific procedures are as follows:

int myAge = 0;

int a = 20

void remAge(int a){

my age = a;

}

Specific functions are described as follows:

int myAge = 0; //Define and initialize my age to 0;

Int a = 20/* defines that variable a is equal to 20*/

Void /* return value type is no return value type */ remAge /* function name */(int a /* passed in parameter */) {

my age = a; //Internal implementation method, note that there is no return to return! ! !

}

There are many topics about functions, so I won't introduce them here. My purpose is to let you know how the function works for a while! Pave the way for the following discussion!

1.3 Pointer and reference:

Pointers and references are available in C++, but not in JAVA. The operation of memory is cancelled in JAVA, and the following things also cancel the operation of operator overload. But later I will introduce some functions such as operator overloading. References are mainly used for passing function parameters. So I won't introduce it too much here. They are all very practical, and interested students can refer to C++ related books.

1.4 operators and control statements:

I'd better read the relevant books myself, so I won't go into details here!

2. In-depth discussion of object-oriented:

2. Internal details of1"Type":

With the above knowledge, we can now dig deep into the internal implementation of the class. I will focus on the knowledge points about classes and objects. Before that, I hope you can make sure that you have fully mastered the basic contents introduced above!

Yes, the biggest feature of object-oriented programming language is that it can write its own data types to solve problems better. I think I have to help you understand the relationship between classes, objects, attributes and methods! As I said before, people can do nothing, because "people" is just an abstract concept, it is not a real "thing", and this "thing" is the so-called object. Only the object can go to work. What about class? Class is the description of the object! Objects are generated from classes! At this point, the object has all the properties and methods described by this class. -Be sure to understand this sentence! ! !

Maybe you're a little overwhelmed, that's all right! Have a good aftertaste, let me give another example! For example, a TV set has a working schematic diagram, so what is a TV set? As long as we can realize all the functions of the working schematic diagram, we call it a TV set. Do you think so? But the schematic diagram of the TV set can't work, that is, this schematic diagram can't watch programs, and only the "entity" of the TV set-the so-called object-can watch programs, that is, it is really meaningful after generating objects from classes! Before you start working. At this point, the TV has all the attributes and methods described in the TV schematic diagram! See, hehe!

As I mentioned earlier, a class is a collection of properties and methods. These properties and methods can be declared as private, public or protected, and they describe the access control of class members. Let me make an introduction respectively:

1.public: After the variable is declared as public, it can be accessed directly through the object, and everything is exposed! In other words, others can directly obtain your credit card password.

2.private: It would be much better if the variable was declared as private. To get my credit card password, the object must call a special method to get it.

3. Protected: We will discuss it when introducing inheritance.

4. Default control accessor (friendly): it exists in Java, but not in C++.

In order to achieve data encapsulation and improve data security, we usually declare the properties of the class as private and the methods of the class as public. In this way, the object can directly call all the methods defined in the class. When the object wants to modify or obtain its own properties, it must call the defined special methods to realize it. Think about it, will you publish your credit card password? Ha ha! Therefore, what we advocate is: "object adjustment method, method changes attribute";

2.2 View memory allocation through examples:

Speaking of which, let's look at an example! For example, now we are going to write a company employee management system. What do you think is the most suitable data type? I think it's employees! But in a process-oriented language, this is not allowed, because it can only use the internal data types in the language! And employees are not in this internal data type! Some people may say that c language can use struct, so pay attention! After all, it is the foundation of the class! If you used to be a C or B programmer, please forget it and let's see how to use classes to realize it!

The employees of the company are a special group of human beings. In addition to all the features and methods of human beings, it has additional features and methods, such as her salary, credit card password, schedule and so on. , these characteristics and work content, workload and so on. How do we define this class in the computer? Next, I'll write out its format and show you what it looks like in the computer!

/* I need to declare again that I use JAVA format, which is very different from C++ in syntax format! There are many differences in many details and internal operations, but they are really similar in thought.

//employee.java

Public employees {

Private string name; //Employee name

Private age; //Employee age

Private sex; //Gender of employees

Private floating salary; //Employee salary

Private Boer lunch; //Staff lunch

//... and so on

Public void heater(){ // This method is used to handle employees' lunches.

Lunch = true;

}

Public void setName(String a){ // This method is to modify the employee's name.

name = a;

}

Public String getName(){ // This method is to get the employee's name.

Returns the name;

}

//... and so on

}

In this way, we define the data types we need. Now, let's see what it can do and how it works!

What I want to do is that there is a one-man army called "Jingwei" in the studio. I modify the name and output it. See what I do!

Note: Please observe carefully how the object calls this method, which uses the "."operator! In fact, this "."operator is used when an object calls a public property or method.

But in C++, if a pointer of the same type is defined, "->" will be used when calling the method of this object. Operator. Please refer to related books for more details!

//workstation.java

Import java.awt.graphics;

Import java.applet.applet;

Public workstation extension applet {

Jingwei of private employees; //The declaration of the object does not allocate memory at this time!

public void init(){

Jingwei = new employee (); /* Creating an object at this time will call the constructor, which will be introduced later */

jingwei . set name(" jw "); //Set my name

}

Public blank paint (figure g)

G.drawString ("My age is" +jingwei.getName (), 10,10); //Show my age

}

}

The output result is:

My name is jw.

The string is located in the output window where the x axis is 10 px and the y axis is 10px.

What I have to do now is to do a big dissection of the above program, so that you can see clearly what is going on! I can show you the compilation from time to time, hehe, neither can I:)

First, let's look at our user-defined data type employee. When it is applied, it is no different from the data of int type. We all need to create variables (objects), but the former is defined by ourselves and then built in. There are many properties and methods in the Employee class. At this point, we can't directly use the object we created to call its properties for modification. Because it is a private protected type! If I want to change my name, I will call the method of setName () with an object, and if I want to get the name, I will call the method of getName (). We completely follow the route, that is, "the object adjusts the method and the method changes the attribute."

Well, I really believe that you have understood what is going on! Ha ha! Raise the sail and move on!

Now let's look at the workstation class. This is a main class, which tastes similar to the main () function in C++. Among them, in JAVA, a file can only have one and only one main class, declared by public! Just like there must be a main () function in C++.

Let's look at the first sentence of this class! Jingwei of private employees; The function of this statement is to declare an employee's object, longitude and latitude (no declaration is needed in C++). What I want to tell you is the difference between "declaration" and "definition". The statement only tells the computer that there will be such a variable (object), and does not allocate memory for this variable (object) in memory! Memory is allocated to a variable (object) only when it is defined. (It should be noted that the init () method completes the initialization operation, and the object is defined here to allocate memory to the object. The start () method is used to start the main thread of the browser, and the paint () method is used to display the interface of Apple. Applet need these, but applications don't. Of course, they are not needed in C++. For more information about them, please refer to related books)

Then, it is practical to set an object and operate on it. Never think about "trying to operate on a class!" As I said before, the principle of TV can't watch TV! This is meaningless! Look at this statement: Jingwei = new employee (); It means to define an object of employee type, Jingwei. At this point, what I want to tell you is: "What do the Jingwei want?" . It has all the properties and methods described by the class. Let me list them for you:

/* All employee objects have these properties. Every time an object is created, a new memory block is allocated to store these properties of the corresponding object. I mean, every object has its own unique copy.

Private string name; //Employee name

Private age; //Employee age

Private sex; //Gender of employees

Private floating salary; //Employee salary

Private Boer lunch; //Staff lunch

/* All employee objects have these methods. But */there is only one copy.

Public void heater(){ // This method is used to handle employees' lunches.

Lunch = true;

}

Public void setName(String a){ // This method is to modify the employee's name.

name = a;

}

Public String getName(){ // This method is to get the employee's name.

Returns the name;

}

/* However, in fact, when creating this object, the computer only allocated memory to all properties of this object, but not to methods. There is only one method, which belongs to all objects, so no matter how many objects are created, the computer will only allocate a piece of memory for one method. */

I think I'd better give an example, or you'll faint. Ha ha!

Look at my sentence "Private Buer Lunch". Every employee in the company should bring a meal regardless of lunch. Let's think of it this way now. The space in the company is the total memory capacity, and your desk is a part of the memory in the computer (every employee has one, which is allocated when the object is created). You take your lunch to the company and put it on your desk. "Lunch" occupies a corner of your desk (a memory capacity of your own "object"). This lunch belongs only to yourself, and so does everyone else! So every employee (object) needs a fast space (memory) to store his lunch (attributes). The same is true in computers. Every time an object is created, a new piece of memory is allocated to put the attribute "lunch-lunch" (all attributes of the object).

The computer will only allocate memory for the properties of the object. Because every object is different! Just like the lunch you brought to the company is different from the lunch I brought to the company! But the method is different. The dishes brought in the morning are cold at noon and need to be heated in the microwave oven. You don't need to bring a microwave oven. The company has (only takes up a piece of space in the company). It's on the lunch table. Whose microwave oven do you think belongs to? It belongs to all employees! Because every employee can use it. You don't have to bring one to every employee. Therefore, every employee (object) has a lunch (attribute), but all employees (object) have only one microwave oven (method). All staff (objects) can change the hot and cold state of their lunch (attributes) through this microwave oven (method). All roads lead to the same goal! In a computer, all objects use only one method! Every object has an attribute because every object is different. Don't tell me you don't understand, or I'll hit the wall, hehe:)

2.3 In-depth discussion of functions:

2.3. 1 constructor, default constructor, default constructor

For the above example, it has been able to complete most of the work, but it is not perfect enough, and there are still many details to be perfected! Some students may have noticed that when I finished creating the object "Jingwei", all the attributes of this object were empty, that is, the name, age, gender, salary and lunch of this object were undecided. And if you want to add all these attributes, you have to use the object to call the corresponding method to modify them one by one! God, this is simply too much trouble! When we create an object, is there any good way to complete the assignment of attributes? Oh, no, it should be said that it is the initialization of attributes. Of course, there is no problem, which requires the so-called builder!

Constructor is the most special function in the class, just the opposite of destructor!

In terms of characteristics: 1. It is the only function in the programming language that has no return value type.

2. Its name must be exactly the same as the class name.

3. It must be declared as a public type.

4. You can overload the constructor.

5. The object will be called automatically when it is created.

Functionally speaking: 1. It initializes the properties in the class.

In fact, for the above program, we didn't define the constructor ourselves. However, in this case, the system automatically defines a "default constructor" for us. He automatically assigns numeric variables to 0, Boolean row variables to false, and so on (but in C++, the default constructor does not initialize its members). If the programmer defines a constructor, the system will not add a default constructor for your program. (It is recommended to define the constructor yourself instead of using the default constructor. )

Let's look at an example! This is more clear!

//employee.java

Public employees {

Private string name; //Employee name

Private age; //Employee age

Private sex; //Gender of employees

Private floating salary; //Employee salary

Private Boer lunch; //Staff lunch

//... and so on

Public employee(){ // This is the "default" constructor.

Name = "jw// Set employee name.

Age = 20; //Set employee age

Sex = "M// Set employee gender.

Salary =100; //Set employee salary

Lunch = holiday; //Set employee lunch

}

Public void heater(){ // This method is used to handle employees' lunches.

Lunch = true;

}

//... and so on

};

In this way, when we create the object "Jingwei", all its properties are initialized! Obviously, this has greatly improved the work efficiency, but it still does not meet the requirements. Think about it, what will happen if we create a second object of this type now? Tell you, except for the "name" of the object (this name is not the name in the object attribute, but the name of the object itself), all its "attribute values" are the same! For example, now we create a second object, flashmagic, but I will find that all the properties of this object are exactly the same as those of Jingwei. And we can only use the object method to change the writing properties! Obviously, this method is not good! We need a way to assign "the value we want" to the properties of an object when it is created.

As you can see, the default constructor is powerless. What we need is a constructor with parameters. When we create an object, we pass the parameters to the constructor, so that we can complete the above functions! With no evidence, let's look at an example:

//employee.java

Public employees {

Private string name; //Employee name

Private age; //Employee age

Private sex; //Gender of employees

Private floating salary; //Employee salary

Private Boer lunch; //Staff lunch

//... and so on

Public employee (string n, int a, char s, float e, boolean l){// Look at this constructor.

name = n; //Set employee name

Age = a;; //Set employee age

Sex = s;; //Set employee gender

Salary = e;; //Set employee salary

Lunch = l;; //Set employee lunch

}

Public void heater(){ // This method is used to handle employees' lunches.

Lunch = true;

}

//... and so on

};

In this way, when we create an object, we can give it the value we want. Obviously, this is much more convenient. Oh, great! I haven't told you how to create it yet! Haha, turn a few pages forward and you will see this sentence:

Jingwei = new employee (); This is to create an object, and we change it to.

Jingwei = new employee ("Jingwei", 20,' m', 100, false); In this way, all the work is finished, hehe! When we create an object, we are given the "initial value" we want. )

2.3.2 Overloaded constructor:

I'd better give you the concept first, so that you can have a concept, and then we can discuss it.

In JAVA:

1. function overload is to declare multiple methods with the same name in a class, but their parameter numbers and parameter types are different.

2. Function refactoring refers to declaring a method with the same name as the parent class in a subclass, thus covering the method of the parent class. Refactoring solves the difference between subclasses and parent classes. (I will explain in detail when discussing inheritance)

In C++:

The concept of 1 The same is true of digital overloading.

2. The concept of refactoring is different. The virtual function in C++ is more powerful. More details are good here, too much introduction!

In fact, you are no stranger to the concept of overloading, and I believe you have been exposed to it in programming. Ha ha! Let's give an example of operator overloading, and you will understand (JAVA does not support this function) that we have defined three integer variables:

int i 1=2,i2=3,i3 = 0;

i3 = i 1+I2;

At this time i3 = 5;; The plus sign realizes the operation function of adding two numbers. However, we now want to define three string variables:

String str 1="jing ",str2="wei ",str3 =

str 3 = str 1+str 2;

At this time str3 = "jingwei"; The plus sign realizes the operation function of adding two strings. It is also a plus sign. You can add two integer variables together or two string variables together. The same operator realizes different functions-this is the so-called operator overload (hey hey, I said you must have seen it:)! No, just like a word in Chinese has multiple meanings! I need to explain that operator overloading in C++ is not that simple. For example, we can add two user-defined objects and assign values. This writing is concise and practical. Of course, there are too many topics about operator overloading, so I am interested in reading again!

We turn the topic of operators to functions, and we always emphasize that "the object calls the method"-the object actually calls the name of the method. And now we should consider the overload method, that is, defining multiple functions with the same name, so that the computer will not be confused when calling? I don't think so, hehe, because only the function name is the same, and we will pass the parameters to him when calling the function. Without parameters, it is also a kind of parameter transfer parameter information (information means no parameters)! However, due to the differences in parameter types, parameter numbers and return value types, can we distinguish functions with the same name?