Object-oriented Thinking-do not regret it !, Object orientation does not look regret

Source: Internet
Author: User
Tags java format

Object-oriented Thinking-do not regret it !, Object orientation does not look regret

Object-oriented Thinking-do not regret it!

Preface:
This document aims to help friends better understand object-oriented programming. This allows later users to avoid detours. However, many vulnerabilities and errors are inevitable, and we also ask our predecessors to provide valuable suggestions for changes. After all, the Exchange conference will keep us updated.
Technology is changing with each passing day, and he will not wait for your growth. Technology must be used to communicate with others. Learning is a subjective understanding of yourself! The Exchange Conference makes progress faster. I think that if the computer architecture does not undergo revolutionary changes, the language of the program we are currently using will be a constant change! What do you learn about programming? Thoughts! After mastering a programming language (preferably an object-oriented language) and then engaging in other programming languages, you will find that the process is so cloudification! Why? You have mastered the idea of programming and learned other things. It is nothing more than learning a new syntax format.
I am not here to discuss with you how to use C ++ or JAVA, nor to discuss with you how to learn them. What I want to discuss with you is how to understand object-oriented. It mainly involves "classes, objects, inheritance, attributes, methods, static, overload, hiding, refactoring, declaration, definition, initialization, and assignment". There are many related technologies. generation after generation, this gives you a way To get started. For more detailed technical details, please refer to other related books for further research! Because I am only discussing with you how to better understand object-oriented!
How to Improve efficiency? Reuse resources and use other people's things. This is a good idea! For you, the greatest resource is confidence and enthusiasm! Well, let's join in the object-oriented programming for a better chance!
Note: I used JAVA to write all program instances in this article. Of course, it is similar in C ++. I will point it out in different places!
Note: The text in the article should be black, indicating that the text should be blue, the text should be highlighted in orange, and the text should be marked in red!

Body:

1. Basic concepts:
A Preliminary Study on 1.1 categories and objects
I want to talk about process-oriented languages and object-oriented languages. The first thing I want to tell him is class and object! -------- "What is the world composed ?" Different people may have different answers to this question. If it's a chemist, he might tell you, "Are you still asking? The world is composed of molecules, atoms, ions, and other chemicals ". What if it's a painter? He may tell you, "the world is made up of different colors "....... Well, there are different opinions! But it would be much more interesting for a classifier to think about it. He will tell you that "the world is made up of different types of things and things! As an object-oriented programmer, we need to consider the problem from the perspective of the classifier! Yes, the world is composed of animals, plants, etc. Animals are divided into single-cell animals, multi-cell animals, and mammals ...... That's all!
Now, from the abstract point of view, Let's define the "class! I mean, from an abstract point of view, you say, "What is human ?" First, let's take a look at some of the features of humans, including attributes (some parameters, values) and methods (some actions, what can they do !). Each person has attributes such as height, weight, age, and blood type. People will work, people will walk upright, people will use their own minds to create tools and so on! The reason why humans are different from other types of animals is that everyone has the attributes and methods of human beings. "Human" is just an abstract concept. It is just a concept. It is a non-existent entity! However, all objects with attributes and methods of the "human" group are called! This object "person" is actually an entity! Everyone is an object of the human group. Why are tigers not human beings? Because it does not have the attributes and Methods of the human group, the tiger does not walk upright, does not use tools, and so on! So tigers are not people!
The ------- class describes a group of objects with the same features (attributes) and same behavior (methods. In programs, classes are actually data types! For example, integer or decimal number. Integers also have a set of features and behaviors. The difference between a process-oriented language and an object-oriented language is that a process-oriented language does not allow programmers to define their own data types, but can only use the built-in data types in the program! In order to simulate the real world and better solve the problem, we often need to create the data types necessary to solve the problem! Object-Oriented programming provides us with solutions.

1.2 built-in data types and functions:
When storing data, a computer program must track three basic attributes:
1. Where information is stored;
2. What is the stored value;
3. What type of stored information;
Let's take a look at the built-in data types in the programming language! (Well, this is not easy to say, because each language has its own unique data type, but this is a minority, for example, there is byte data in JAVA, I don't have it in C ++. I hope you can give it a different picture !) For example, integer "int" and floating point data "float "! String "String", as well as arrays and struct. However, when writing a program, we will create a type of variable or constant as needed. For example, we can do this because we need to create an integer variable I is 5, int I = 5; as needed, I may change the I value, that is, assign a new value to it, for example, let it and 6, you can change it to I = 6 in the desired place. We know that the amount of variable that can change in the value is called a variable. The amount that will not change is called a constant. In C ++, the count keyword is used for declaration, while in JAVA, the final keyword is used for declaration. Since the declaration formats in different languages are different, I will not describe them here. For details, refer to relevant books!
Here we will mainly discuss the function. We can think of the function as a "black box implementing a specific function" ------- this function is set by you. For example: now I ask you "how much is 2 + 3 equal "? I believe that you can answer me 5 quickly. Let's analyze the information contained in this sentence! First, I want to think of your brain as a black box. I don't know how your brain works (that is, how it operates ), I only care about what information I sent to you? What information have you done? And what information did you return to me? Note that each method returns a message to the caller, except the constructor (I will introduce it in detail later ). Now I need to think of myself as a programmer. What about you? Of course it's a computer! Computing can be less intelligent than people. It will only run in a specific format agreed in advance. I want it to have the functions described above, I will first define this black box! First, I want to tell this black box that there will be two integers for you (this is the so-called parameter, which is the information the programmer needs to give to the Black Box ), then we need to define the black box to implement the addition of the two integers (this is the processing of the black box on the data, you can do any processing as needed .). At last, mark it and return it to me as an integer value (this is the information that the black box returns to the programmer ). A function is defined in this way. Let's look at the writing format:

Int addnum (int x, int y ){
Return x + y;
}

The specific meaning is as follows:

Int/* return value type */addnum/* method (Black Box) name */(int x, int y/* input parameter */){
Return x + y;/* internal method (to implement the addition operation) and return the return result to the caller */
}

First, pay attention to the "return" statement described above! The return keyword is used to return the information that follows the caller! Just like above, You will answer me only when I ask you. If I don't ask you, you don't have to answer me! In the same way in the computer, where can this function be called? I can only tell you where to call it! Of course, you can change the parameters, return values, and internal implementation as needed. You have to refer to the related documents for details on how to define how to call them! Here I just give you a thought!
Sometimes you may encounter such a problem. I want you to remember that I am 20 years old! Literally, you didn't return me any information! However, in fact, you did return information to me. The content of the information is "no information, that is, no return value type void ". The specific procedure is as follows:

Int myAge = 0;
Int a = 20;
Void remAge (int ){
MyAge =;
}

The specific functions are described as follows:

Int myAge = 0; // define and initialize my age to 0;
Int a = 20;/* define variable a to 20 */
Void/* return value type: no return value type */remAge/* function name */(int a/* input parameter */){
MyAge = a; // internal implementation method. Note that no return is returned !!!
}

There are many other topics about functions. I will not introduce them one by one here. My goal is to let you know what the function is for a while! Pave the way for the following discussion!

1.3 pointer and reference:
Pointers and references exist in C ++, but are not in JAVA. JAVA removes the memory operation and removes the operator overload operation. However, I will introduce some functions such as operator overloading later. References are mainly used to pass function parameters. So I will not introduce it too much here. They are very practical. If you are interested, you can refer to C ++ related books.
1.4 operators and control statements:
Let's take a look at the relevant books by yourself. I will not repeat them here!

2. in-depth exploration of object-oriented:
2.1 internal details of the "type:
With the above knowledge, we can now thoroughly explore the internal implementation of the class. All the knowledge points will be centered around classes and objects. Before that, I hope you will be able to fully understand the basic content described above!
Yes, the biggest feature of the object-oriented programming language is that you can write the data types you need to better solve the problem. I think I must help you figure out the relationships between classes, objects, attributes, and methods "! As I mentioned earlier, the human class cannot do anything, because "human" is just an abstract concept, and it is not a real "thing ", this "thing" is the so-called object. Only the "object" can work. What about classes? Class is the description of the object! The object is generated from the class! In this case, the object has all the attributes and methods described by the class. ------- Be sure to understand this sentence !!!
Maybe you are a little overwhelmed. It doesn't matter! Let me give you another example! For example, TV sets have working principle diagrams. What is TV set? As long as it can implement all functional objects in the working principle diagram, we call it television. Do you think this is the case? However, the TV schematic cannot work, that is, the schematic cannot watch the program. Only the TV "entity-the so-called object" can watch the program. That is to say, after an object is generated from the class, it is truly meaningful! To start work. At this time, the TV has all the properties and methods described in the TV schematic! Okay, huh, huh!
As I mentioned earlier, classes are a set of attributes and methods. These attributes and methods can be declared as private, public, or protected. They describe access control for class members. Next I will introduce them separately:
1. public: After declaring a variable as a public type, you can directly access it through an object. Everything is exposed! That is to say, your credit card password can be directly obtained by others.
2. private: If the variable is declared as private, it will be much better. To get my credit card password, the object must call a dedicated method.
3. protected (protected): We will discuss it again when introducing inheritance.
4. default access control character (friendly): // in JAVA, but not in C ++.
To encapsulate data and improve data security, we generally declare the class attributes as private and the class methods 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 attributes, it must call a defined dedicated method. Think about it. Will you publish your credit card password? Haha! Therefore, we advocate "Object adjustment methods and methods to change attributes ";
2.2 view memory allocation through instances:
Let's look at an instance! For example, if we want to write an employee management system for a company, what is the most suitable data type? I think it's an employee! However, in a process-oriented language, this is not allowed because it can only use internal data types in the language! Employees are not in this internal data type! Some people may say they can use struct in C! After all, it is the foundation of the class! If you used to be a C or B programmer, please forget this. Let's take a look at how to implement it with classes!
A company's employees are a special group of humans. In addition to all the features and methods of humans, it also has additional features and methods, for example, she has her salary, credit card password, schedule, and so on. These features and work content, workload, and so on. How can we define this class in a computer? Next I will write its format to show you what it looks like in a computer!

/* What I need to declare again here is that I use the JAVA format, which is different from the C ++ syntax! Many details and internal operations have many differences, but the thoughts are indeed similar */
// Employee. java
Public class employee {
Private String name; // employee name
Private int age; // employee age
Private char sex; // employee gender
Private float emolument; // employee salary
Private boolean lunch; // employee lunch
//...... And so on.
Public void heater () {// This method is used to process employees' lunch
Lunch = true;
}
Public void setName (String a) {// This method modifies the employee name
Name =;
}
Public String getName () {// This method is used to get the employee name
Return name;
}
//...... And so on.
}

In this way, the data types we need are defined. Now, let's see what it can do and how it works!
What I want to do is, there is a light pole commander in the studio named "jingwei". I changed its name and output it to see how I did it!
Note: Observe how an object calls a method. It uses the "." operator! In fact, the "." operator is used when an object calls a public property or method.
However, if a pointer of the same type is defined in C ++, the "->" operator is used when the pointer calls the method of this object. For more details, see related books!

// Workstation. java
Import java. awt. Graphics;
Import java. applet. Applet;
Public class workstation extends Applet {
Private employee jingwei; // object declaration. No memory is allocated at this time!
Public void init (){
Jingwei = new employee ();/* the constructor will be called when an object is created. Please wait for a while */
Jingwei. setName ("jw"); // set my name
}
Public void paint (Graphics g ){
G. drawString ("my age is" + jingwei. getName (), 10, 10); // display my age
}
}

The output result is:

My name is jw

The string is at the position where the x axis of the output window is 10 px and the y axis is 10 px.
What I want to do now is to make a big anatomy of the above program so that you can see exactly what it is! (I can show you the Assembly from time to time. Oh, I won't do that either :)

First, let's take a look at our custom data type employee. In the application, it is no different from the int type data. In the same way, we need to create variables (objects ), however, the former is self-defined, and then it is built in. The Employee class has many attributes and many methods. At this time, we cannot directly use the created object to call its attributes for modification. Because it is private-protected! If I want to modify my name, I need to call the setName () method with an object, and if I want to get my name, I need to call the getName () method. We are completely walking by route. This route is "Object adjustment method, method change attribute"
Okay, I really believe you have understood what it is! Haha! Start your flight and move on!
Now let's take a look at the workstation class. This is a main class, similar to the main () function in C ++. In JAVA, only one primary class is allowed for a file. The primary class is declared as public! It must have the same main () function as C ++.
Let's take a look at the first statement in this class! Private employee jingwei; the role of this statement is to declare the jingwei object of an employee (no declaration is required in C ++ ). What I want to tell you is the difference between "Declaration" and "Definition. The declaration only tells the computer that there will be such a variable (object). In the memory, it does not allocate memory for this variable (object! The variable (object) is allocated memory only when defined. (It must be noted that the init () method is used to complete initialization. The object is defined here and memory is allocated 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 Apple interface. These are required by the Applet, but they are not required by the Application. Of course, they are not required in C ++. For more information, see related books)
Then we start to define an object. Therefore, operations on the jingwei object will have practical significance. Never think like this: "trying to operate on the class !" As I said above, the principle of television is not to watch TV! This is meaningless! Let's look at this statement jingwei = new employee (); it means to define a jingwei object of the employee type. What I want to tell you at this time is: "What does jingwei have ". It has all the attributes and methods described by the class. I will list them for you one by one:

/* All employee objects have these attributes. Each time an object is created, a new memory is allocated to store these attributes of the object. I mean, each object has its own unique copy */
Private String name; // employee name
Private int age; // employee age
Private char sex; // employee gender
Private float emolument; // employee salary
Private boolean lunch; // employee lunch
/* All employee objects have these methods. But there is only one copy in the memory */
Public void heater () {// This method is used to process employees' lunch
Lunch = true;
}
Public void setName (String a) {// This method modifies the employee name
Name =;
}
Public String getName () {// This method is used to get the employee name
Return name;
}
/* However, in fact, when the jingwei object is created, the computer only allocates memory to all attributes of the object, but does not allocate memory to the method. There is only one method that belongs to all objects. Therefore, no matter how many objects are created, the computer will allocate only one piece of memory for one method. */
I 'd like to give you an example. Otherwise, you will not be able to faint. Haha!
Let's look at my statement "private boolean lunch;" for lunch, every employee needs to bring meals. We now think that the company's space is all the memory capacity, and your desk is part of the memory in the computer (each employee has a copy, which is allocated when the object is created ). You brought lunch to your company and put it on your desk. "Lunch" occupies the corner of your desk (occupies the memory capacity of your "object ). This lunch is only for you, and others only for herself! Therefore, every employee (object) needs a fast space (memory) to store their lunch (attribute ). This is also true in the computer. Every time you create an object, A new piece of memory will be allocated in the memory to put the "lunch-lunch" attribute (all attributes of the object ).
The computer only allocates memory for the properties of the object. Because each object is different! Just like the lunch you bring to your company is different from the lunch I bring to your company! But the method is different. The lunch in the morning is cold at noon. You need to use a microwave oven for heating. The microwave oven does not need to be carried by you. The company has a space (only a part of the company's space) and it is placed on the lunch desk. Who does the microwave oven belong? It belongs to all employees! Because every employee can use it. Instead of bringing one copy to every employee. It can be seen that each employee (object) has a lunch (attribute), but all employees (objects) only have one microwave oven (method ). All staff members can use this microwave oven (method) to change the hot and cold states of their lunch (properties. The same way! This is also true in the computer. There is only one method for all objects! Attribute is a copy of each object, because each object has different attributes. Don't tell me that you still don't understand, or I will hit the wall, haha :)

2.3 explore functions in depth:

2.3.1 constructor, default constructor, and default constructor

For the above instance, it can already complete most of the work, but it is still not perfect, there are many details to be improved! Some people may have noticed that when I create the "jingwei" object, all the attributes of this object are empty, that is: the object name is uncertain, the age is uncertain, the gender is uncertain, the salary is uncertain, and the lunch is uncertain. If we want to add these attributes, we need to use the object to call the corresponding methods and modify them one by one! Oh, my God, this is too much trouble! Is there any good way to assign values to attributes while creating objects? Oh no. Should I say it is the initialization of the attribute? Of course, no problem. This requires the so-called constructor!
Constructor is the most special function in the class. It is opposite to the function of the Destructor!
In terms of features: 1. It is the only function in programming languages that has no return value type.
2. Its name and class name must be exactly the same.
3. It must be declared as a public type.
4. You can reload the constructor.
5. It is automatically called when an object is created.
Function: 1. It initializes the attributes in the class.
In fact, for the above program, we do not have a self-defined constructor. However, in this case, the system will automatically define a "default constructor" for us ". It automatically assigns a value to 0 and a Boolean variable to false (but in C ++, the default constructor does not initialize its members ). If the programmer defines the constructor, the system will no longer add a default function for your program. (Here, we advocate self-defining constructor rather than using the default constructor of the system)
Check an instance! This is clear!

// Employee. java

Public class employee {

Private String name; // employee name

Private int age; // employee age

Private char sex; // employee gender

Private float emolument; // employee salary

Private boolean lunch; // employee lunch

//...... And so on.

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

Name = "jw"; // set employee name

Age = 20; // set the employee's age

Sex = "M"; // sets the employee gender.

Emolument = 100; // set employee salaries

Lunch = false; // set employee lunch

}

Public void heater () {// This method is used to process employees' lunch

Lunch = true;

}

//...... And so on.

};

In this way, when we create the "jingwei" object, all its attributes are also initialized! Obviously, this greatly improves the work efficiency, but it still does not meet the requirements. Think about what will happen when we create the second object of this type? It tells you that except for the object's "name" (this name is not the name in the object property, but the name of the object itself), all its "property values" are the same! For example, now we create the second object flashmagic, but I will find that all the attributes of this object are exactly the same as those of jingwei. However, we can only use the object method to change the write attribute! Obviously, this method is not good! We need a way to assign the desired value to the object property when creating the object ".
As you can see, the default constructor is powerless. What we need is a constructor with parameters. When creating an object, we pass the parameters to the constructor so that the above functions can be completed! Let's just look at an instance:

// Employee. java

Public class employee {

Private String name; // employee name

Private int age; // employee age

Private char sex; // employee gender

Private float emolument; // employee salary

Private boolean lunch; // employee lunch

//...... And so on.

Public employee (String n, int a, char s, float e, boolean l) {// check this constructor.

Name = n; // set employee name

Age = a; // set the employee's age

Sex = s; // set employee gender

Emolument = e; // set employee salaries

Lunch = l; // set employee lunch

}

Public void heater () {// This method is used to process employees' lunch

Lunch = true;

}

//...... And so on.

};

In this way, when creating an object, we can give it the value we want. Obviously, this is much more convenient. Oh, right! I haven't told you how to create it yet! Haha, you will see this sentence a few pages forward:
Jingwei = new employee (); this is to create an object, and we change it
Jingwei = new employee ("jingwei", 20, 'M', 100, false); in this way, all the work has been completed! (When creating an object, the desired "Initial Value" is assigned ")

2.3.2 overload constructors:
Let me give you the concept first, so that you can understand it, and we will discuss it later.
In JAVA:
1. Function overload is a class that declares multiple methods with the same name, but there are different parameter numbers and parameter types.
2. Function refactoring refers to declaring a method with the same name as the parent class in the subclass, thus overwriting the methods of the parent class. Refactoring solves the difference between the subclass and the parent class. (I will explain it in detail when discussing inheritance)
In C ++:
1. The concept of a number overload is the same.
2. The concept of refactoring may be different. The functions in C ++ are more huge. For more details, here is a great introduction!
In fact, you are no stranger to the concept of heavy load, and I believe you have been familiar with it in programming. Haha! Let's take an example of operator overloading and you will understand that (JAVA does not support this function) We define three integer variables:

Int i1 = 2, i2 = 3, i3 = 0;
I3 = i1 + i2;

In this case, i3 = 5; the plus sign is used to add two numbers. However, we need to define three string variables:

String str1 = "jing", str2 = "wei", str3 = "";
Str3 = str1 + str2;

In this case, str3 = "jingwei"; the plus sign is used to add two strings. The plus sign can be used to add two integer variables or two string variables. The same operator implements different functions ------ this is called Operator Overloading (hey, I say you have seen it :)! It's not like a word in Chinese! I need to note that operator overloading in C ++ is not that simple. For example, we can add two custom objects and assign values. This is concise and clear, and is very practical. Of course, there are too many topics about operator reload. If you are interested, read the book!
We turn the topic of operators to functions, and we have always stressed that "object calling method"-the object actually calls the "name" of the method ". Now, we need to reload the method, that is, to define multiple functions with the same name, so that the computer will not be confused during the call? I don't think so. Haha, because the function name is the same, we will pass the parameter to the function when calling the function. There is neither a parameter nor a parameter transfer parameter information (the information is no parameter )! However, because of the different types of parameters, parameter quantities, and return values, we can differentiate functions with the same name.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.