4.2 Classs and Objects 4.2.1 Classs are in object-oriented languages, the class is an important concept. Object-oriented methods classify all processing objects. Objects with the same properties are classified as one. For example, there are many students in schools, and each student is an object, and "Students" is a class, which contains all people studying at school. In the Java language, the object is a set of sets of the properties and operation methods of the object, where attributes indicate the status of the object, and the method indicates the behavior of the object. Class is the definition of an object. What attributes and methods have an object, which is determined by a class. From a programming perspective, the class is a composite data type, which encapsulates a set of variables and methods (functions). Declare a general form of a class as follows: Modifier Class class name {// Category} In the modifier illustrates the properties of the class, it can be public, abstract, final, etc. The meaning of these modifiers will be introduced in the subsequent chapter. The specification is a statement of a member variable and a member method. The declaration of modifiers and categories is optional. Below is a statement of "people" class, although the type is empty: Class Person {} 4.2.2 Object Objects and classes are different but closely concealed concepts. Class is the definition of the object, the object is generated by the class. The relationship between classes and objects is better than the relationship between the mold and the product in the casting workshop. There is only one mold, but in this mold can cast a lot of molded products, the shape of the mold determines the shape of the cast product. In the Java language, use the new key to generate objects, usually: Class name object name = new class name ([parameter]); the object name here can be arbitrary legally java identifier. The name name of the NEW key is labeled as a constructor (function). The default, the simplest constructor is without parameters, or can customize different forms of construction methods for future needs. The following example uses the previous Person class to generate two Person objects Mike and John: person mike = new person (); Person John = new person (); use new person () Generate an object not only allocated memory space not only Some initialization work, the object includes not only the specific value of the attributes, but the specific value of the attribute. If you do not assign a value to the property, the virtual machine will automatically give them the default initial value of the corresponding data type. The process of generating an object is also called instantiation, so an object is an instance. Mike and John are object names. The object name is used to reference objects, and the variables and methods in the object can be referenced by the object name, so the object name is also referred to as reference (Reference). Quoted similar to the concept of pointers in C / C , unlike pointers, references are not directly pointing to the memory location where the object is located, but it contains information about the memory address. There is no pointer in Java to make memory operations often cause unpredictable errors, and it is also because of this, Java is considered a "secure" programming language. The objects generated in the previous example are as follows: Figure 4-1 References to objects In some special cases, it may generate an instance but does not need to be referenced, which can be instantiated directly with NEW. As shown below: New Person (); New Person (); The above two liner generates two Person objects, but each generated object occupies different memory spaces, changing the status of one of the objects that does not affect other objects. . Just like a blank is poured with a mold, although the two blanks look very like, they are definitely two different blank. 4.2.3 Member Variables In object-oriented ideas, usually use properties to describe the characteristics of the object.
In the programming language, this group is represented by a variable from the attribute that belongs to a certain type of object, such as the height, body weight, name, etc. used to indicate the characteristics of the person, and can separately use different types of variables: Double type Height, Float Weight, String Name is represented. These variables that belong to the class are called the class of member variables. The general form of statement is as follows: modifier data type member variable name; where modifiers illustrate the properties of the class's member variable, it can be public, protected, private, static, transient, final, volatile, and more. The type of member variable can be a Java built-in or a custom complex data type, including simple types, classes, interfaces, arrays. For example, describing a person having a property can be represented by a House type variable house, which is the user-defined class (complex data type). The general form of calling member variables is: instance name. The Member Variable Name is a statement of a "person" class, and the class name is Person. Description "People" member variables are: Height, Weight, Sex, Name, Age, etc., as well as a statement of property House. [Example 4-1] Class Person {Double Height; Float Weight; Char Sex; String Name; Int Age; House House; NEW PERSON (); p_bill.age = 26; p_bill.Height = 180; p_bill.weight = 145; p_bill.sex = 'm'; p_bill.heme = "Bill Gates"; p_bill.house = new house ();} } The Person class has 6 member variables, five of which are simple data types, 1 is a composite data type House. A object that references P_BILL is generated in the main function of class E4_1. This p_bill can be accessed by this person's age, height, weight, etc. attributes. The above program can be placed all in one source file, the source file name must be E4_1. A source file of Java allows multiple classes to exist, but the file name must be consistent with the public class, and only one PUBLIC class can be used in a source file. Member variables do not require explicit initialization. In fact, they still have initialized, called implicit initialization. No explicit initialized member variables are automatically initialized when allocating storage spaces, and various types of variables are paid to the default initialization value, as shown below: Byte 0 Short 0 INT 0 long 0l float 0.0f double 0.0d Char '/ u0000' (NULL) Boolean False All Composite Data Type NULL The following example prints the implicit initialization Person class member variable.
[Example 4-2] Class Person {Double Height; Float Weight; CHAR SEX; String Name; Int Age; House House;} Class House {} public class e4_2 {public static void main (string args []) {person p_bill = NEW PERSON (); system.out.println (p_bill.pe); system.out.println (p_bill.height); system.out.println (p_bill.weight); system.out.println (p_bill.sex); system. .out.println; system.out.println (p_bill.house);}} The result is: 0 0.0 0.0 NULL NULL 4.2.4 Members Method Objects can be used to change the object's properties, or Use information from other objects and send messages to other objects. From a programming perspective, the class is a collection of a set of Java statements. The method and process language C, PASCAL, etc. are actually a concept. However, in the language of purely objects like Java, the "function" can only be included in the class, and it is used to describe the behavior of the class, generally referred to as a method. The general form of the definition method is as follows: The modifier return type method name ([Parameter Type Parameter, ...]) [THROWS exception list] {// method} square brackets are optional. The modifier can be public, protected, private, static, final, abstract, native, synchronized, etc. The return type can either a simple data type or a composite data type (array, class or interface). If the method does not return a value, you must also use the VoID declaration in the return type. Alternatively, this method returns a VOID type. For example: void setHeight () {}, however, once the method declares a return type, the method must return and declare the same amount of data in the method of RETURN keywords. Throws is used to declare an abnormality, see Chapter VII Opening and Assembly.
The general format of the call object method is: reference name. Method name ([Parameter list]); the following example is a complete definition of a Person class: [Example 4-3] Public Class E4_3 {public static void main (String args " ) {Person P = New Person (); P.Setage (30); system.out.println (p.getage ());}} Class Person {Private Double Height; Private CHAR SEX; private string name ; private int age; public void setAge (int age) {this.age = age;} public void setHeight (double height) {this.height = height;} public void setName (String name) {this.name = name;} public void setSex (char sex) {this.sex = sex;} public void setWeight (float weight) {this.weight = weight;} public int getAge () {return age;} public float getWeight () {return weight;} Public char Getsex () {return getName () {return getHe;} public double getHeight () {return height;}} In the previous example, each member variable has two methods and corresponding, respectively Is the set and get method. The SET method is used to change the value of the member variable. The return type is Void, and the GET method is used to obtain the value of the member variable, and the RETURN is used in their method bodies to return the data type consistent with the method declaration. The THIS key in this example is used to reference the current object. The method of use and the use of functions in the process language are the same. However, in the Java language, there is no method other than class, all methods are in the class, so it is generally called by the object name. Some static methods can be called by class name. In the above-mentioned MAIN method of the E4_3 class, a Person object named P is generated, and the setage () method sets the age, and finally calls the age of p. The method can contain all legal Java instructions. The local variables used in the method can be declared, and its scope is only inside the method, and when the method call ends, the local variable is invalid. If the local variable name of the method and the name of the class of the class of the class is the same name, the member variables of the class are hidden, that is, the failure is currently valid. Local variables.
[Example 4-4] Public Class E4_4 {INT X = 0, Y = 0, Z = 0; Void Action (INT X) {x = 11; // Parameter XY = 12; // Class Member Variable Y INT Z = 13; // Method Internal Variable Z System.out.Println ("in the init () method inside:"); system.out.println ("member variable:" "x =" THIS "Y =" THIS.Y "Z =" this.z); System.out.println ("Local Variable:" "x =" x "z =" z);} public static void main (String args []) {E4_4 E = New E4_4 (); System.out.Println ("Call before:"); System.out.Println ("Member Variable:" "x =" E.x "Y =" E.Y "z =" ez); E.Action (1); system.out.println ("After calling:"); system.out.println ("Member Variable: " x = " E.x " Y = " E.Y " Z = " EZ);}} The output of the program is: call before call: member variable: x = 0 y = 0 z = 0 In the init () method inside: Member variable: x = 0 y = 12 z = 0 local variable: x = 11 z = 13 After calling: member variable: x = 0 y = 12 z = 0 In the above example method, parameter X and new defined variable Z scope are only The Action method is inside, because they and class member variables x, z is the same name, so class member variables are covered. The parameter X and local variables z are called inside the Action method, not the class member variable. But this does not mean that it cannot be called to a member variable within the method. In the above example, we used this. This represents the current object (instance) of the method. So you can use this to call all members variables and members of the object. The method can bring multiple parameters, separated by commas. For simple data types, Java implementation is the value of value delivery, method receives parameters, but does not change the value of the arguments. For composite data types, Java implementation is a referenced pass, which can change the value of the original parameter. The following example shows the difference between the simple data type and the reference data type.