Object-oriented technology foundation

zhaozj2021-02-16  54

3.1 Object-Oriented Technology Foundation 3.1.1 Object-Oriented Basic Concept Object-Oriented Basic Thoughts Objects is an emerging programming method, or a new programming specification (paradigm), its basic idea is Program design using basic concepts such as objects, classes, inheritance, packages, messages. Software systems are constructed from things (ie, objects) existing in the real world, and use human natural thinking as possible in the system configuration. Developing a software is to solve some problems, the business scope involved in these issues is called the software problem. Its application is not only software, but also computer architecture and artificial intelligence. 1. Basic concept of objects 2. Basic concept of class 3. news

1. Basic concept of the object

Objects are an entity used in the system to describe objective things, which is a basic unit constituting the system. An object consists of a set of services that operate on this group of properties. From a more abstract point of view, the object is a problem domain or an abstraction of certain things in the domain, which reflects the information and the role of the information that needs to be saved in the system; it is a set of attributes and have the right to have these properties A set of services for operations. The objective world is composed of objects and objects. Active object is a set of properties and a set of packages of a set of services, where at least one service does not need to receive messages (called active services).

3.1.2 Objective Basic Features 1. Packaging 2. Inheritance 3. Polymorphism

1. Encapsulation

The encapsulation is to combine the objects and services of the object into an independent identical unit, and consider the internal details of the object, including two meanings: ◇ Combine all the properties of the object and all services to form an indiscrunable independent Unit (ie object). ◇ Information hidden, that is, the internal details of the object, and form a boundary [or form a barrier], only the limited external interface is associated with the outside. The principle of encapsulation is reflected in the software that requires that some parts other than the object cannot access the internal data (attribute) of the object, thereby effectively avoiding external errors to "cross-infection", making software errors locally, Greatly reduce the difficulty of check-in and misconduct. 2. Inheritance

Special classes have all the properties and services of its general class, called a special type of inheritance of a general class. For example, ships, passenger ships; people, adults. A class can be a special class of a plurality of general classes, which inherits attributes and services from a plurality of general classes, which are called multi-inheritance. For example, the passenger is a special class of ships and passenger tools. In Java language, usually we call a general class as a parent class (Superclass, a super class), special type as subclass (Subclass).

3. Polymorphism

The polymorphism of the object refers to a different data type or a different behavior that can have different data types after the attribute or service defined in the general class is inherited. This makes different semantics in the same attribute or service in a general class and its special classes. For example: "Draw" method, "elliptical" and "polygon" of "Geometric Graphics" are subclasses of "geometric map", and their "drawing" method is different. 3.1.3 Object-Oriented Program Design Method OOA-Object Oriented Analysis Object - OOD-Object Oriented Design Object-Oriented Design OOI-Object Oriented Implementation Object-Oriented Implementation

3.2 Object-Oriented Properties of Java Language 3.2.1 Class Class is an important composite data type in Java, which is the basic element of the Java program. It encapsulates the status and method of an object, which is the original shape of this type of object. An implementation of a class includes two parts: class declarations and categories. 1. Class declaration 2. Cymbol 3. Member variable 4. Member method 5. Method is overloaded 6. Construction method 1. Class Declaration: [PUBLIC] [Abstract | Final] Class classname [extends superclassname] {...} where the modifier public, abstract, final illustrates the properties of the class, classname is the class, superclassname is the parent of the class. The name of the class, InterfaCenameList is the list of interfaces implemented by the class. 2. The category is defined as follows: Class classname {[public | protected | private] [static] [final] [TRANSIENT] [Volatile] Type Variablename; // Member Variables [PUBLIC | Protected | Private] [static] [Final | Abstract ] [Native] [Synchronized] Returntype methodname ([paramlist]) [THROWS ExceptionList] {statements} // member method} 3. The statement of member variable members is as follows: [public | protected | private] [static] [final] [TRANSIENT] [Volatile] Type VariableName; // member variable wherein static: static variable (class variable); relative to instance variables Final: Constant TRANSIENT: Temporary variables for object archive volatile: contribute variables for concurrent thread sharing 4. The implementation of the member method method includes two parts: method declarations and methods. [PUBLIC | Protected | Private] [Static] [Final | Abstract] [Native] [Synchronized] ReturntyPE MethodName ([paramlist]) [THROWS ExceptionList] // Method Declaration {Statements} // Method Body Method Declaration Meaning: static: Class method, can call the Abstract: Abstract method through class name, no method final: method cannot be overridden Native: Integrated other languages ​​code SYNCHRONIZED: Control multiple concurrent threads access ◇ Method declaration

Method declarations include method names, return types, and external parameters. The type of the parameter can be a simple data type or a composite data type (also known as reference data type). For simple data types, Java implements values ​​for values, method receiving parameters, but cannot change the value of these parameters. If you want to change the value of the parameter, use the reference data type because the reference data type passes to the method is the address of the data in the memory, and the operation of the data can change the value of the data. Example 3-1 illustrates the difference between the simple data type and the reference data.

[Example 3-1] Import java.io. *; public class passtest {float ptvalue; public static void main (string args []) {int val; passtest pt = new passtest (); VAL = 11; system.out. Println ("Original Int Value IS:" VAL); Pt.Changeint (VAL); // Value Parameter System.out.Println ("Int ValueAfter Change IS: VAL); / * Value parameter value modification, There is no value of the value of the value * / pt.ptValue = 101f; system.out.println ("Original PtValue IS: Pt.PtValue); Pt.ChangeObjValue (PT); // Reference Type Parameters System.out.println ("PtValue After Change IS:" Pt.PtValue); / * Reference parameter value modification, change the value of reference parameters * /} public void change (int value) {value = 55; // In-way The parameter is modified} public void change {ref.ptValue = 99f; / / Internally modified the reference parameters inside the method}}

◇ Method Body Method is an implementation of the method, which includes a declaration of local variables and all legal Java instructions. The role of the local variable declared in the method is inside the method. If local variables are the same name with the member variable of the class, the member variables of the class are hidden. Example 3-2 illustrates the role of local variables Z and class member variables Z.

[Example 3-2] Import java.io. *; class variable {int x = 0, y = 0, z = 0; // member variable void init (int x, int y) {this.x = x THIS.Y = Y; int Z = 5; // Local variable system.out.println ("** in init **"); system.out.println ("x =" x "y =" y "z =" z);}} public class variabletest {public static void main (string args []) {variable v = new variable (); system.out.println ("** before init"); system .out.println ("x =" v.x "y =" v.y "z =" vz); v.init (20, 30); system.out.println ("**After init * * "); System.out.println (" x = " v.x " y = " v.y " z = " vz);}} We use this this because init () The parameter name of the method is the same as the name of the member variable x, y of the class, and the parameter name hides member variables, so in the method, in order to distinguish parameters and members variables, we must use this. THIS ---- uses the current object in one method, which is the object that calls the method. The return value must be consistent with the return type, or identical, or its subclass. When the return type is an interface, the return value must implement the interface. 5. Method Overloading method overload refers to multiple methods to enjoy the same name, but the parameters of these methods must be different, or the number of parameters is different, or the parameter type is different. The return type cannot be used to distinguish the method of overload. The distinction between parameter type must be sufficient, for example, cannot be the same simple type, such as INT and long.

[Example 3-3] Import java.io. *; class methodoverloading {void receiver (int i) {system.out.println ("receive one int data"); system.out.println ("i =" i) } Void receive (int x, int y) {system.out.println ("Receive Two int Datas"); system.out.println ("x =" x "y =" y);}}}} public class MethodoverLoadingTest {public static void main (string args []) {methodoverloading mo = new methodoverloading (); mthodoverloading (); mo.receive (1); mo.RecEcept (2, 3);}} 6. Construction method ◇ Construction method is a special method. Each class in Java has a constructor to initialize an object of the class. ◇ Construction method has the same name as the class name, and does not return any data types. ◇ Overload is often used in the construction method. ◇ Construction method can only call [Example 3-4] Class Point {INT X, Y; Point () {x = 0; y = 0;} Point (int x, int y) {this.x = X; THIS.Y = Y;}}

3.2.2 Object class instantiation can generate an object, and an object interacts through message delivery. Message delivery activates the method of the specified object to change its status or make it generate a certain behavior. An object's life cycle includes three phases: generation, use, and elimination. 1. Generation of the object 2. Use of the object 3. Clear of the object

1. Generation of objects of objects include declaration, instantiation, and initialization. The format is: type objectname = new type ([paramlist]); ◇ declaration: Type ObjectName declaration does not assign memory space for the object, but only assigns a reference space; the reference is similar to the pointer, it is a 32-bit address space, it The value points to a middle data structure, which stores information about the data type and the address where the current object is located, and the actual memory address in which the object is located is uncomfortable, which guarantees security.

◇ Instantiation: Operator New is an object allocated memory space, and it calls the structure of the object, returns a reference; the different objects of a class occupy different memory spaces. ◇ Generate: Perform a construction method, initialization; the corresponding constructor is called according to the parameters. 2. The use of the object through the operator "." You can implement calls and methods of variables. Variables and methods can limit access to it by setting access. ◇ Call the variable format of the object: ObjectReference.variable ObjectReference is a generated object, or an expression example of an object: PX = 10; tx = new point () .x; ◇ Call the object method: ObjectReference .MethodName ([paramlist]); for example: p.move (30, 20); new point () .move (30, 20); 3. Clearance of the object When there is no reference to an object, the object becomes one Useless objects. Java's garbage collector automatically scans the dynamic memory of the object, collects and releases the objects that are not referenced as garbage. System.gc (); when the system memory is exhausted or called System.gc () requires garbage collection threads to run synchronously with the system. 3.2.3 Object-Oriented Characteristics The Java language has three typical object-oriented features: package, inheritance, and polymorphism, which will be described in detail below. 1. Packaging 2. Inheritance 3. Polymorphism 4. other

1. Encapsulation

In the Java language, the object is a package of a set of variables and related methods, where variables indicate the state of the object, and the method indicates the behavior of the object. The modular and information hidden by the encapsulation of the object. Implement information hidden in the class in a certain access to a member of the class.

◇ Primitive definition: class classname {[public | protected | private] [static] [final] [TRANSIENT] [Volatile] TYPE VARIABLENAME; // Member Variable [PUBLIC | Protected | Private] [static] [Final | Abstract] [native] [synchronized] returntype methodname ([paramlist]) [THROWS EXCEPTIONLIST] {statements} // Member Method}

◇ j 的 j j 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 的 不同,. 1) A member of the Private class is limited to Private, which can only be accessed by this class itself. If a class constructor is declared as Private, other classes cannot generate an instance of the class. 2) The DEFAULT class does not add any access to the default access state, which can be accessed by this class itself and the class in the same package. 3) The Protected class is limited to a Protected member, which can be accessed by this class itself, its subclass, its subclass (including subcategories in the same package) and all other classes in the same package. 4) The public class is defined as a member of Public, can be accessed by all classes. [Table 3-1] Comparison of the scope of limits in java

Same class

Same package

Subcounds of different packages

Different bags

Private

*

DEFAULT

*

*

protected

*

*

*

public

*

*

*

*

2. The inheritance is reused by inheritance. All classes in Java are obtained by directly or indirectly inheriting the java.lang.Object class. The class obtained by inheritance is called subclasses, and the class inherited is called a parent class. Subclasses cannot inherit the members variables and methods of access to visitors in the parent class. Subclasses can rewrite the method of parent class, and naming the member variables with the parent class. However, Java does not support multiple inheritance, namely a class from multiple superclatrifies. ◇ Creating a sub-format: Class SubClass Extends Superclass {...} ◇ The hidden method of the member variables The rewrite subclavab can change the status and behavior of the parent class by hiding the members variables of the parent class and rewriting the parent class. Itself state and behavior. For example: class superclass {int x; ... void setX () {x = 0;} ...} Class Subclass Extends superclass {int x; // hide the parent class variable x ... Void setX () {// Rewrite the father Class SETX () x = 5;} ... Note: The method of rewriting in the subclass and the way to be rewritten in the parent class must have the same name, the same parameter table and the same return type, just a function The body is different. ◇ SUPER JAVA is enabled by Super Java to implement access to parent class members, and Super is used to reference the parent class of the current object. SUPER's use has three situations: 1) Access the parent class hidden member variable, such as: super.variable; 2) Call the method of being rewritten in the parent class, such as: super.method ([paramlist]); 3) call The constructor of the parent class, such as: super ([paramlist]);

[Example 3-5] Import java.io. *; class superclass {int x; superclass () {x = 3; system.out.println ("in superclass: x =" x);} void dosomething ()} System.out.println ("in superclass.dosomething ()");}} class subclass extends superclass {int x; subclass () {super (); // call the parent class constructor x = 5; // super ) The first sentence in the method System.Out.Println ("in subclass: x =" x);} void dosomething () {super.dosomething (); // Call the parent class method system.out. Println ("in subclass.dosomething ()"); system.out.println ("super.x =" super.x "sub.x =" x);}} public class inheritance {public static void main (String Args []) {subclass subc = new subclass (); Subc.dosomething ();}} 3. Polymorphisms In Java Language, polymorphism is embodied in two aspects: dynamic polymorphism (compiled time polymorphism) and method rewriting by method overloading (compile time polymorphism) and method rewriting achieved dynamic polymorphism (running polymorphism). 1) Compile time polymorphism in the compilation phase, which is the overloaded method, and the compiler will staticly determine the corresponding method according to the different parameters. 2) Running polymorphisms Sub-objects can be used as a parent class object due to subclasses inheriting all parent classes (except for private). Wherever the program uses the parent class object, you can use a sub-object instead. An object can call a subclass by reference to an instance of a subclass. ◇ Calling principle of rewriting method: Java runtime system determines which method of call according to the instance of calling this method. An example of a subclass, if the subclass rewrites the method of the parent class, the method of running the subclass when the system is runtime; if the subclass inherits the method of the parent class (not rewriting), the runtime system calls the parent class. Methods. In Example 3-6, the parent class object A reference is an instance of subclasses, so the CallME method of subclass B is called when Java runtime.

[Example 3-6] Import java.io. *; class a {void callme () {system.out.println ("INSIDE A's Callme () Method");}} Class B Extends A {Void Callme () {system .out.println ("INSIDE B'S Callme () Method");}} public class dispatch {public static void main (string args []) {a a = new b (); a.callme ();}} ◇ Method Principles should follow when rewritten: 1) After rewritten, the method cannot be more stringent access to the way (the same). 2) Remote method does not have more exceptions to the method of rewriting. 4. Other ◇ Final Keyword Final keywords can be modified, and the members variables and members of the class, but Final's functionality is different. 1) Final modified member variable: final modified variable, it becomes a constant, such as Final Type VariableName; when modified member variables, the initial value is given, while the local variable is not required. 2) Final modified member method: final modification method, then this method cannot be rewritten in subclass of Final ReturNType MethodName (paramlist) {...}

3) Final Class: Final Trunge Class, the class cannot be inherited Final Class FinalClassName {...} Instance members and class members with static keywords can declare class variables and class methods, their formats are as follows: Static Type Classvar; Static ReturntyPE ClassMethod {paramlist}) {...} If Static keyword modifications are not available in the statement, declare the instance variable and instance method. 1) Example variables and instance variables of each object each object allocate memory, access these instance variables through this object, and different instance variables are different. Class variables are only assigned memory only when generating the first object, and all instance objects share the same class variable, each instance object changes to class variables, affects other instance objects. Class variables can be accessed directly through class names without having to be mailed to an instance object, or can access class variables through instance objects. 2) Example method and class method example method can operate the instance variable of the current object, or operate the class variable, the instance method is called by the instance object. However, the class method cannot access instance variables and can only access class variables. The class method can be called directly by the class name, or the instance object is called. This or super keyword cannot be used in the class method. Example 3-7 is an example of example membership and class members.

[Example 3-7] Class Member {static int classvar; int instancevar; static void setclassvar (int i) {classvar = i; // instancevar = i; // type method can not access instance variable} static int getClassvar () {Return Classvar;} void setInstancevar (INT i) {classvar = i; // instance method can not only access class variables, but also instance variables instancevar = i;} int getInstancevar () {Return Instancevar;}} public class membertest {public static void Main (string args []) {member m1 = new member (); member m2 = new member (); m1.setClassvar (1); m2.setclassvar (2); system.out.println ("m1.classvar =" m1.GetClassvar () "m2.classvar =" m2.getClassvar ()); m2.setinstancevar (11); m2.setinstancevar (22); system.out.println ("m1.instancevar =" m1. GetInstanceVar () "m2.instancevar =" m2.GetInstanceVar ());}}} ◇ 类 java.LANG.Object class java.LANG.Object The root of the class hierarchy in the Java development environment, all other classes are direct These are inherited indirectly. This class defines some of the most basic status and behavior. Below, we introduce some common methods. Equals (): Compares whether two objects (references) are the same. GetClass (): Returns the representation of the class corresponding to the object run, so that the corresponding information can be obtained. TOSTRING (): String representation used to return objects. Finalize (): Used to clear the object before garbage collection. NOTIFY (), NotifyAll (), Wait (): The same 3.2.4 abstraction and interface 1 in multi-threaded process 1. Abstract class 2. interface

1. In the abstract class Java language, with the Abstract keyword to modify a class, this class is called an abstract class, which is called an abstract method when modifying a method with the Abstract keyword. The format is as follows: Abstract Class AbstractClass {...} // Abstrained Abstract Returntype AbstractMethod ([paramlist]) // Abstract method The abstract class must be inherited, the abstract method must be rewritten. Abstract methods only need to declare, no need; abstract classes cannot be instantiated, abstract classes do not have to include abstract methods. If the class contains an abstract method, the class must be defined as an abstract class. 2. The interface interface is one of the abstract classes, only the definition of constants and methods, without the implementation of variables and methods, and its method is an abstract method. It is reflected in the following aspects: ◇ Implement the same behavior of unrelated classes through the interface without considering the relationship between these classes. ◇ 指 Individual methods that need to be implemented through the interface. ◇ Learn the interactive interface of the object through the interface without having to understand the class corresponding to the object. 1) Definition of the interface of the interface includes interface declarations and interfaces. The format of the interface declaration is as follows: [public] interface interface {...} Extendsuperinterface] {...} Extends clause is basically the same, and the difference is that an interface can have multiple parent interfaces, separated by commas, and one Class can only have a parent class. The interface includes a constant definition and method defining a constant definition format: Type Name = value; the constant is implemented in multiple class shares of the interface; with the properties of Public, Final, Static. Method Body definition format is: (has a public and abstract attribute) Returntype methodname ([paramlist]); 2) The implementation of the interface is used in the statement of the class to represent a class to use an interface, which can be used in the specimen Constants defined in the interface, and all methods defined in the interface must be implemented. A class can implement multiple interfaces, separated by commas in the Implements clause. 3) The interface of the interface type is used as a reference type. Any instance of a class that implements the interface can be stored in a variable of the interface type, and the method in the interface implemented by these variables can be accessed. 3.2.5 Internal class 1. Definition and use of internal classes 2. Definition and use of anonymous class 3. Advantages and disadvantages of internal classes 1. The definition and use of internal classes: Internal classes are classes in the internal nested definition of a class, which can be a member of other classes, or within the internal definition of a statement block, you can also define anonymous inside the expression. The internal class has the following characteristics: ◇ Generally used within the class or statement block, you must give a complete name when referenced to it externally. Name cannot be the same as the class name containing it. ◇ You can use the statics and instances of the class containing its classes, or the local variables of the method thereof can also be used. ◇ You can define Abstract. ◇ can be declared as private or protected. ◇ If it is declared as static, it becomes a top layer, and local variables cannot be used again. ◇ If you want to declare any Static member in Inner Class, the Inner Class must declare to static. Example 3-8 is an example of how the internal class is used, where two internal classes are defined: MouseMotionrandler and MouseEventHandler are used to handle mouse mobile events and mouse points.

[Example 3-8] import java.awt *;. Import java.awt.event *;. Public class TwoListenInner {private Frame f; private TextField tf; public static void main (String args []) {TwoListenInner that = new TwoListenInner (); (); PUBLIC VOID Go () {f = new frame ("two listener example"); F.Add ("North", New Label ("Click and Drag The")); TF = New TextField (30); F.Add ("South", TF); F.AddmouseMotionListener (new mousemotionrandler ()); f.SetSize (300, 300); F.SetVisible (True } Public class mousemotionage {public void mousedragged (mouseEvent e) {string s = "mouse Dragging: x =" E.GETX () "y =" E.Gety (); tf.settext (s }}} Public class mouseeventhandler extends mouseadapter {public void mouseentered (mouseEvent e) {string s = "the mouse entered"; tf.settext (s);} public void mouseexited (Mouseeven T E) {string s = "the mouse left the building"; tf.settext (s);}}} The classmate can run this program and see its operation results. When you move your mouse into Frame: "The mouse entered"; when you drag the mouse in Frame, the text box will appear: "Mouse Dragging: x = 64 y = 117"; when the mouse is left When the text box, the text box appears: "The Mouse Left the building". 2. The definition and use of anonymous classes:

Anonymous classes are a special internal class that contains a complete class definition in an expression. Through the modification of the GO () part of the Some statement in Example 6-7, we can see the use of anonymous classes. Public void Go () {f = new frame ("two listener example"); F.Add ("North", New Label ("Click and Drag the Mouse"); TF = New TextField (30); f.add ("South", TF); F.AddmouseMotionListener (new mousemotionrandler () {/ * defines an anonymous class, the class name is not explicitly given, just this class is the subclass of the MouseMotionraler class * / public void mousedragged (MouseEvent e) {string s = "mouse Dragging: x =" E.GETX () "y =" E.Gety (); tf.settext (s);}}); f.addmouseristener (new mouseeventhandler () ); F.setsize (300, 300); f.setVisible (true);} 3. Advantages of internal classes: ◇ Advantages: Save the size of the bytecode file after compilation ◇ Disadvantage: make the program structure unclear [this tandem] class is the basic element of the Java language object-oriented programming, it defines an object Structure and function. The Java class contains member variables and members. There are two of the members variables, with Static key modified variables for class variables, no STITIC modified variables are instance variables. Accordingly, there are two kinds of member methods, with Static modified as class methods, no STITIC modified as an example method. The instance method can operate not only the instance variable of the current object, but also operate the class variable; but the class method can only access the class variable. The instance variable and example method must be called by an instance object, and the class variable and class method can be called by instance objects, but can also be called directly by the class name. Java encapsulates the data in a class by declaring variables in a large bracket defined, called a member variable. In order to solve the problem that the class name may be the same, the package is provided in Java to manage class space. Packaging, inheritance, and polymorphisms are three-oriented three characteristics in the Java language. The interface is a unique data type in the Java language. Due to the existence of the interface, the Java language does not support multiple inheritance of multiple inheritance. Internal classes are classes that refer to internal nested definitions of a class.

转载请注明原文地址:https://www.9cbs.com/read-19303.html

New Post(0)