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 overloading. 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. Neither a parameter nor a parameter transfer parameter information (the information is "No parameter )! However, because of the different parameter types, parameter quantities, and return value types, we can differentiate functions with the same name! There is only one purpose, and more functions are implemented in a simple way. Let's take an example. Reload the constructor!
Public class employee {
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 Employee () {// note that this function has no parameters
Name = "JW ";
Age = 20;
Sex = 'W ';
Emolument = 99;
Lunch = true
}
//...... And so on.
};
Look, there are two functions with the same name in a class. But when we use them, how does the system know which version of the function we are calling? As I said, you can determine the parameter type, parameter quantity, and return value type of the function. Now let's try again. We create one of the two objects to call the constructor with parameters, and the second object to call the default constructor. Let's take a look at the results:
Jingwei = new employee ("Jingwei", 20, 'M', 100, false);/* the constructor with parameters is called when this object is created */
Flashmagic = new employee (); // create this object to call but save the value of the constructor
What is the result? Let's take a look!
In the Jingwei object: flashmagic:
Name Jingwei name JW
Age 20 age 20
Sex M sex w
Emolument 100 emolument 99
Lunch false lunch true
See, although they are two functions with the same name, they have completed different work content. Haha! Let's just look at the function overload here. I believe you have a big impression, and more detailed content still requires your efforts!
The heavy-duty common function is similar to the heavy-duty constructor, but he has an extra this pointer! This is generally a reference to the current object. If more than two objects are involved, this pointer is used. Each member function has a this pointer, which is a hidden parameter. This pointer only calls its object! As I said, there is only one method, and all objects have their own attributes. When an object calls a method first, how does it determine that the called method is not its own attribute? This requires the this pointer to demonstrate the power of the gods.
We will not discuss too much about copying constructors, inline functions, virtual functions, templates, and so on, because JAVA does not seem to have such problems. However, in C ++, functions defined in the class are automatically converted to inline functions, which seems to be in conflict with the ideas I mentioned earlier. Because the purpose of inline functions is to reduce the overhead of function calls! Haha! I did not go around either! Which of the following are some suggestions! Thank you!
2.3.3 initialization and assignment
Here, I would like to remind you that initialization and assignment are two completely different concepts. When creating a class, the constructor of this class is called to initialize the properties of the object. It would be easier to assign this object to other objects of the same type later. Assign values directly in Java, because the pointer is removed in Java, and there is no deep copy or pre-copy problem of the pointer. In C ++, the constructor and operator overload need to be copied. Because Java does not involve these things, I will not introduce them too much. For more information, see related books!
2.3.4 analyze functions:
The pointer is no longer supported in Java, so you cannot feel its importance, because the system will automatically release the memory for you. In C ++, everything is manual. A new pointer is added to the constructor, And the delete pointer is required in the analysis function.
2.3.5 static:
Now let's take a look at what static means!
To declare a variable or function as static, the keyword "static" is required. The purpose of static declaration is to "allocate a single bucket to a certain attribute or method of all objects of a class ". Static data belongs to a class and does not belong to any object. When static data is declared, the system allocates memory space for it, instead of waiting until the object is created. Let's take an example to help you better understand it.
Continue with the above example. Remember that I just said that employees can use a microwave oven for hot meals. Now we need to find a glove. After all, it is impossible to take the hot meal out of the microwave oven. I define a glove as a Boolean variable, which has two states: clean and dirty. Think about who the glove belongs? All objects? No! Because only methods can belong to all objects. It belongs to a class. Like the microwave oven method, it has only one copy in the memory, and all objects can be modified through the method. The next modification is based on the last modification! I mean, when an employee gets dirty his/her gloves, the next employee gets dirty. After this employee cleans his glove, It is clean when others use it again! That's all you need!
There is nothing to say about static functions. The feeling is that it also belongs to the class and the memory allocated at the time of definition. You can use the class name to call the API directly. Other member functions are no different from common member functions. However, in Java, static member functions can only modify static attributes, static attributes can be modified by all member functions. But there are not so many things in C ++!
2.4 inheritance
Inheritance is easy to understand. Its biggest benefit is "code reuse", which greatly improves work efficiency. For example, you will understand. The world's first black and white TV sets have their own working principles. However, people developed color TVs based on them. Color TV inherits all the features and methods of black and white TV sets! Because it can display both color images and black and white images. However, it has many differences with black and white TVs, in terms of working principles. The color TV and the matrix color circuit are used to separate the color signal from three colors (RGB), so that the color image can be displayed. The black and white TV does not have this circuit, and even if it receives a color signal, it cannot display a color image. Color TVs are derived from black and white TVs. Therefore, black and white TVs are the parent class, and color TVs are both child classes. color TVs inherit all the features and methods of black and white TVs. Let's see what it looks like in the computer:
// Bwtv. Java parent class definition
Public class bwtv {
Private int;
Public bwtv (){
A = 1;
}
Public changebwtv (int I ){
A = I;
}
}
// CTV. Java subclass Definition
Class CTV exntends bwtv {// note the keyword "extends"
Private int B;
Public CTV (){
B = 2;
}
Public changetcv (int x ){
B = X;
}
}
With the above definition, let's see what data they all have.
Bwtv data includes CTV data
Private int A private int
Private int B
Public changebwtv (); Public changebwtv ()
Public changectv ();
As you can see, subclass has all the methods and attributes of the parent class. Note that the keyword "extends" indicates inheritance. The ":" operator is used in C ++. It means the same. However, there are many problems. The first is access permissions. The subclass object has all the attributes and methods of the parent class. Right? It must be correct! (This is not the case in Java. He said that he only inherits non-private attributes and methods. I think this sentence is wrong !) However, subclass objects cannot directly access the private attributes or methods of the parent class. They can only be accessed through the Public member functions of the parent class. If you modify the attribute value of the parent class. Then it is modified. I mean: the value of the private property of the parent class will change as the subclass object calls the public method of the parent class to modify the corresponding property! (There is a domain problem here. All modifications are made in the subclass, and the attributes of the parent class inherited by the subclass are modified (in the domain of the subclass, in this case, the parent class is copied to the subclass .). The attributes of the parent class defined in the program do not change (in the parent class domain ),)
Second, constructor. When creating a subclass object, you must first call the constructor of the parent class and then call the constructor of the subclass. After all, the constructor of the subclass does not include the initialization function of the attributes of the parent class! (From this point of view, my point of view is correct. "The subclass object has all the attributes and methods of the parent class.") Of course, the order of function calls is the opposite!
Now let's talk about the keyword protected, which means that for an object, the variables declared as protected are private, and for the subclass parent class, variables declared as protected are public.
Now we have another problem. If we define an int type variable A in the subclass, so when we create a subclass object, do we call the subclass definition or the parent class definition? This involves data hiding. I can tell you that it is definitely the variable A of the called subclass. This is because the subclass hides the variable with the same name as the parent class. What if it is a method? This involves refactoring. As mentioned above, "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 ." It must be declared that, in Java, after the subclass hides the parent class attribute and overwrites the parent class method, in the subclass, subclass objects can only call attributes and methods of subclasses. To call the attributes and methods of the parent class, you must use the super key. This is not the case in C ++. Because it has virtual functions
Virtual functions are very interesting in C ++. We can declare the function to be rewritten as a virtual function and use the keyword virtual to declare it. In this way. If we assume that cwinapp is such a base class, it defines a member (virtual) function as initinstance () and another (virtual) function as initapplication (). If I derive a subclass of cmywinapp from cwinapp and modify the member function initinstance. We have not modified the initapplication () member function. Now we create the cmywinapp class function theapp, and we create a pointer * PAPP pointing to this object theapp. At this point:
PAPP-> initinstance () // the pointer calls the virtual method of the subclass cmywinapp.
PAPP-> initapplication () // virtual method of the parent class cwinapp when the pointer is called
Because the subclass does not modify the method of the parent class, the virtual method of the parent class is called. This involves the problem of your table. The positioning of this article will not be discussed here!
The type conversion problem between the parent class and the Child class object is that there is no error when the child class object is converted to the parent class object. Because the subclass contains all the attributes and methods of the parent class, it is hard to say that the parent class is converted to the subclass. This will also involve the issue of virtual tables and will not be discussed!
Java no longer supports multi-inheritance, that is, a class is inherited from more than two classes, but it does not support the interface concept ". I will not introduce it too much here!
There is no difficulty in abstract base classes! One of his major concepts is that, as the parent class of many classes, objects are not defined and only used for derivation!
I can only do this. If you can understand the above six or seven achievements, it will be my greatest return, haha! As I said at the beginning, I just gave you a rough idea. As for the internal implementation details, you still need to continue to work hard. There are still a lot of content about programming languages. It is really a small student who has limited personal abilities and cannot take care of it all. But as a beginner, these things are basic. One thing I need to remind you is, don't expect to understand anything in the first or second time! Come on :)
04.4.29 Han Jingwei
I am willing to keep in touch with you. I would be grateful if you can give valuable comments and suggestions on this article. My email address is:
Onegenius@126.com
Or leave me a message on QQ (86228551 --- garbled wandering soul. h)
Reference from: http://www.vikosoft.net//trackback.asp? Tbid = 1, 523