Lecture 2

xiaoxiao2021-03-06  42

Chap1. Introduction 1, Java history and development Java is an interpretation type, object-oriented programming language. History: In 1991, Sun Microsystem's Jame Gosling, Bill Joe, etc. developed a software called Oak on a TV, control oven and other household consumer electronics. Development: Networking application, the class library is constantly rich, the performance is continuously improved, and the application are continuously expanded. (Since 1994) Application: Suitable for developing various applications, especially based on network-based applications, embedded applications, etc. 2, Java language characteristics Java = "C " - "Complexity and Singular" "Security and Portability" (1) Object-oriented Java language design focuses on objects and their interfaces, it provides a simple class mechanism And dynamically interface models. It encapsulates its status variables and corresponding methods in the object, and the category provides the prototype of the object, and the method can use the method provided by the inheritance mechanism, the subclass can use the method provided by the parent class. Reuse of the code. (2) Operating platform unrelated language definitions: No "depending on the machine" or "determined by the compiler", the last target code is consistent. The Java interpreter generates the bytecode instruction independent of the architecture, as long as the Java runtime system is installed, the Java program can run on any processor. These bytecode instructions correspond to the representation of the Java virtual machine, and the Java interpreter is converted after the bytecode, allowing it to operate at different platforms.

Different operating systems have different virtual machines. It is similar to a small and efficient CPU. Bytecode code is a machine instruction that is unrelated to the platform is a virtual machine. Java byte code runs two ways: Interpreter JUST-IN-TIME (instant compilation): Code generator converts the byte code to the machine code of the machine, and can be executed at a higher speed. (3 Safety issues Java is the language used in a network environment. A secure network should prevent the possibility of the following destruction: n Destruction System Resource N Consumption System Resources N Mining System or Personal Confidential N Harassment Normal Work

Bytecode runs § load code is done by Class (Bytecode) Loader. § The check code is done by bytecode verifier. § Execute code is done by Runtime Interpreter.

(4) Multi-thread Java provides ready-made THREAD, as long as inheriting this class, you can write multithreaded programs. Multi-threading mechanism enables applications to execute parallel, and the synchronization mechanism guarantees the correct operation of shared data. By using multiple threads, program designers can use different threads to complete specific behaviors, without having to adopt global event cycle mechanisms, which easily enable real-time interaction behavior on the network. (5) Portability (across multiple platforms) (6) Distribution (obstacles on space) (7) High performance (relative to other interpretation languages) (8) robust ((9) Java and C and The difference between C § No more global variable § No longer there is #include and #define and other pre-treatment no longer Structure, Union and Typedef, etc. no longer function, no longer have a pointer, no more inheritance § does not There is another goto statement § no longer operator overloading § Cancel automatic type conversion, requires forced conversion § Automatically perform memory management

3. Java development tools include: §javac: Java compiler, used to compile Java programs into bytecode. §Java: Java interpreter, executing a Java application that has been converted into bytecode. §JDB: Java debugger for debugging Java programs. §Javap: Reflexible, restore the class file back to the method and variables. §Javadoc: Document Builder, create an HTML file. §Appletviwer: Applet interpreter, used to explain the Java applet that has been converted into bytecode. 1. Java program structure: § package statement: zero or more, must be placed in the file § IMPORT statement: zero or more, must be placed before all class definitions public classdefinition: zero or a § Classdefinition: zero One or more § interfaceDefinition: zero or more class: at least one class, only one PUBLIC class source file name: If there is a public class, the source file must press this class name identifier: case sensitive

2.Java Application § Class library support: Reference other classes. § Class definition: Define the classes and interfaces required for the program, including variables, methods such as their internals. § Main () method: The application of the application is the same as the position of the main () function in standard C. An application has only one main () method, the main () method must be included in a class, which is the external flag of the application. § Program Note: Similar to C , / * ... * / // ...

3. Java Applet § Class Library Support: Inherited Applet class, reference other classes. § Class definition: Define the classes and interfaces required for the program, including variables, methods such as their internals. §Init () method: initialization, automatic call, only once. §Start () method: After initialization, the re-entry will automatically call. The main body of the applet, in which some tasks or start-related threads can perform tasks, such as a Paint () method, and the like. §Stop () Method: Call when you leave the page where the applet is located to stop consumer system resources.

4.Java Application Example Public Class HelloWorldApp {public static void main (string args []) {system.out.println ("Hello World!");}}

N Editing Storage: File Name and Public Class Name (Declaration with public) To consistent helloworldapp.javan compiler: Javac HelloWorldapp.javan Running: Java HelloWorldAppn Run: Hello World!

Public class helloworldapp {public static void main (string args []) {system.out.println ("Hello World!");}}

§ Declare a class: public class helloworldapp {}, class name first letter uppercase. § There are many ways in a class, the main method is the first method of running the program, the first letter lowercase of the method name. §System.out.println is output to the screen, which is equivalent to Printf (). Class command {public static void main (string args []) {// display command arguments INT i; if (args.length> 0) // Have Some Command Arguments {for (i = 0; i

n Command line parameters: main (string args []), similar to the standard C (int Argc, char * argv []). N-string stitching: "Arg [" i "] =" args [i]. n Compiler: Javac HelloWorldapp.javan Runner (Command Line Parameter Get): Java Commarg First Second Thirdn Run Results: Arg [0] = First Arg [1] = Second Arg [2] = third

5.applet example import java.applet. *; Import java.awt. *; Public class helloapplet extends applet {public string s; public void init () {s = new string ("Hello World!");} Public void Paint (Graphics g) {g.drawstring (s, 25, 25);}}

Editing the deposit: File name and primary class matching code: Javac HelloApplet.java Written HTML file: HelloApplet.html

Hello World </ title> </ head> <applet code = "HelloApplet.class" width = 300 height = 300> </ applet> </ html></p> <p>The Java applet cannot perform and use directly, and must be executed in the browser. § Run Applet program: 1. AppletViewer mytest.html 2. Run § running in the browser: Hello World!</p> <p>Understanding procedures: NIMPORT statement is equivalent to include in C language. N Each applet is a subclass of java.applet.applet, inheriting with Extends. There is no main () method in the Napplet. When the applet is running by the browser, the init (), the start () method is automatically executed, and the PAINT () method is called. N The operation related to the screen output in the applet is implemented via the Graphics object. n One of a Java source file can only have a public class called primary class, and the file name must be with its same name.</p> <p>Import java.util. *; import java.applet. *; import java.text. *; public class mytest extends applet {String S1, S2, S3, S4; Public void init () {S1 = getParameter ("p1"); S2 = getParameter ("p2"); S3 = getParameter ("p3"); S4 = getParameter ("p4");} public void Paint (graphics g) {g.drawstring (S1, 10, 10); G. DrawString (S2, 10, 30); G.drawString (S3, 10, 50); g.drawstring (S4, 10, 70);}}}</p> <p>Editor: File Name and Main Size Compilation Code: Javac MyTest.java Written HTML File: MyTest.html</p> <p><Html> <head> <title> applet parameter test </ title> </ head> <applet code = "mytest.class" width = 300 height = 300> <param name = p1 value = "111111"> <param Name = p2 value = "2222222"> <param name = p3 value = "3333333"> <param name = p4 value = "4444444"> </ applet> </ html></p> <p>§ Run Applet program: 1. AppletViewer mytest.html 2. Run in the browser § Run results: 1111111222222 3333333 4444444</p> <p>Understanding: N Get Applet parameters from the page: S1 = getParameter ("p1"); N setting an applet parameter in the page: <param name = p1 value = "1111111"></p> <p>§ Packages, classes, variables, methods, etc. Name: It is necessary to reflect the respective meaning. The name of the name, IO, AWT class name first letter should be capitalized, helloworldapp variable name first letter should be lowercase, the username method name first letter should be lowercase, setName § program writing format: guarantee good readability, Make the program at a glance. The use of large brackets {} and the alignment of the alignment statement segment In appropriate space lines § Program Note: Help understand the functionality of the program. Class Note Variable Note Method Note Statements Note CHAP2. The Java Language Basis Any programming language is composed of language specification and a series of developers. If the standard C, in addition to the language standards, there are many libraries; MS Visual C provides huge APIs and MFCs. The Java language is no exception, and is also composed of Java Language Specification and Java Development Category (JFC).</p> <p>Learning any programming language, it is to start from these two aspects, especially to use the latter.</p> <p>1, Java Data Type 2, Java Operator and Expression 3, Java Control Statement 4, Java Class Definition Specification 5, Java Array 6, Java Development Category</p> <p>1. Java Data Type (1) Identifier Used Named Name Identifier (Identifier) ​​using each element in the program (Identifier) ​​includes: class name, variable name, constant name, method name, ... Java language The identifier is a character sequence starting with letters, underscore (_), US dollar ($), behind the letter, underline, dollar, numbers. Legal identifier Identifier User_Name_sys_value $ CHANGE Illegal Identifier 2mail Room # Class</p> <p>(2) The reserved word has special meaning and use, which cannot be used as a general identifier, and these identifiers are called reserved words. abstract break byte boolean catch case class char continue default double do else extends false final float for finally if import implements int interface instanceof long length native new null package private protected public final return switch synchronized short static super try true this throw throws threadsafe transient void while</p> <p>(3) Constants use text strings to represent, have different types, its definition format: final type varname = value [, varname [= value] ...]; (4) Basic storage unit in variable program, the definition including variables Name, variable type, and scope of action, defined format is: type varname = value [, varName [= value] ...]; Scope: Refers to a piece of code that can access variables, variables declared in the program Different scopes: local variables, class variables, method parameters, exception processing parameters. In a certain scope, the variable name must be unique. (5) Basic Types of Data Types: All the number of bits of all basic types is determined, and it is not different due to the different operating systems. Data Types The scope of the number of occupies CHAR 16 0 ~ 65535 BYTE 8 -27 ~ 27-1 SHORT 16 -215 ~ 215-1 INT 32 -231 ~ 231-1 Long 64 -263 ~ 263-1 Float 32 3.4e -038 ~ 3.4e 038 Double 64 1.7e-308 ~ 1.7e 308</p> <p>Reference Type: § "Reference" in Java is a location pointing to an object in memory, in essence, is a pointer with strong integrity and security. § When you declare a variable of a class, interface, or array type, the value of that variable is always a reference to an object or a NULL reference. § The pointer is a simple address. Reference In addition to representing the address, it is also available in the epitome of the referenced data object. § The pointer can have , - operation, and reference cannot be operated.</p> <p>Boolean data has only two values ​​true and false, and they do not correspond to any integer value of Boolean variables such as boolean b = true; character constant character constant is a character in single quotes, such as 'A', 'A'; character type variable type is char, which accounts for 16 digits in the machine. The definition of the character type variable is as follows: CHAR C = 'a'; / / Specifies the variable C as a CHAR type, and the first value is 'a'</p> <p>Integral constant 1. Extrameters such as 123, -456, 02. Octoral integers begin with 0, such as 0123 indicate the decimal number 83, and the decimal number of decimers - 9.3. Hexadecimal integer starts with 0x or 0x, such as 0x123 indicates a decimal number 291, and -0x12 represents a decimal number of -18. The integer variable type is Byte, Short, Int or long, Byte accounts for 8 digits in the machine, Short accounts for 16 bits, INT accounts for 32 bits, and Long accounts for 64. Definition of integer variables, as: int x = 123; // Specify variable X is INT type, and the first value is 123 byte b = 8; long y = 123L; long z = 123L;</p> <p>Realistic constant 1. Decimal form consists of numbers and decimal points, and must have a decimal point, such as 0.123, .123, 123., 123.02. Scientific counting method such as: 123E3 or 123E3, where e or e must have a number, and The index behind e or e must be an integer. The real variable type is float or double, float accounts for 32 digits in the machine, and Double accounts for 64 bits. Definition of real variables, such as: float x = 0.123; // Specify variable x is Float type, and the first value is 0.123 double y = 0.123f; double z = 0.123f; public class assign {public static void main (String Args []) {INT X, Y; BYTE B = 6; float z = 1.234f; double w = 1.234; boolean flag = true; char C; c = 'a'; x = 12; y = 300; ... ...}}</p> <p>Automatic type conversion integer, real, characteristic data can be mixed. In the operation, different types of data are first converted to the same type, then the operation is performed, the conversion is low to advanced: low ------------------------------------------------------------------------------------------------------------------------------------------------------ ---------------------------> High Byte, Short, Char-> Int -> long-> float -> Double</p> <p>If you convert from advanced conversion to low, you need to force type conversion, but will result in overflow or accuracy. Such as: int i = 8; byte b = (byte) i;</p> <p>2, Java operators and expressions (1) operator arithmetic operators: , -, *, /,%, , - relational operators:>, <,> =, <=, == ,! = Boolean logic operator:!, &&, | 位 运 运算: >>, <<, >>>, &, |, ^, ~ assignment operator: =, and its expansion assignment operator such as =, =, * =, / =, Etc. Conditional operators:?: Other: Includes component operators, subscript operators [], instance operator instanceOf, memory allocation operator NEW, mandatory type conversion operator (type), method call operator (), etc. Since the length of the data type is determined, there is no length operator SIZEOF.</p> <p>2) Expression expression is a symbol sequence consisting of operands and operators in a certain grammatical form. A constant or a variable name is the simplest expression, which is the value of the constant or variable; the value of the expression can also be used as an operand of other operations to form a more complex expression. Example: X Num1 Num2 a * (B C) D 3.14 x <= (Y Z) X && Y || Z (3) Priority 1)., [], () 9) & 2) , -,!, ~, instanceof 10) ^ 3) New (Type) 11) | 4) *, /,% 12) && 5) , - 13) || 6) >>, >>>, < <14)?: 7)>, <,> =, <= 15) =, =, - =, * =, / =,% =, ^ = 8) ==,! = 16) & =, | =, << =, >> =, >>> =</p> <p>3, Java control statement § Branch statement: IF-Else, Switch§ loop statement: while, do-while, for§ related to program transfer: Break, Continue, Return § Exception processing statement: try-catch-finally, Throw</p> <p>Conditional statement if- else if (boolean-expression1) {statements1;} else if (boolean-expression2) {statements2;} ... else {statementsn</p> <p>Boolean Expressions Boolean-Expression is any expression that returns a Boolean data type and must be (strict than C or C ). Like C or C , there must be a part behind each single statement. In order to enhance the readability of the program, the statement after IF or ELS should be enclosed in {}. The ELSE clause is optional, cannot be used as a statement separately, and it must be used with the IF statement and always associated with the IF pair it closest it.</p> <p>N-Branch Statement Switch Switch (Expression) {Case Value1: {Statements1; Break;} ... Case Valuen: {StatementSn; Break;} [Default: {DefaultStatements;}]} § Expression EXPRESSION Return value must be this Several types: int, Byte, Char, SHORT. § Valuei in the case clause must be constant, and the value in all CASE clauses should be different. § The DEFAULT clause is optional. § BREAK statement is used to make the program out of the Switch statement after performing a CASE branch, that is, the execution of the Switch statement is terminated. If there is no BREAK statement after a CASE branch, the program will no longer perform the next branch. § Switch statements The functionality can be implemented with the IF-ELSE statement, but in some cases, use the Switch statement more short. Cycle statement while (When a loop) [INITIALIZATION] // Initialization condition While (Termination) {// cycle condition body; // cyclic body [Iteration;] // iteration, change cycle condition}</p> <p>When the expression termination is TRUE, the statement in {} is executed, otherwise the loop is terminated.</p> <p>Cycle statement do-while (untid-type loop) [INITIALIZATION] // Initialization condition DO {body; // cyclic body [ITeration;] // iteration, change cycle condition} whiling; // Circulation condition</p> <p>First, the statement in {} is performed. When the expression terminal is TRUE, the statement in {} continues to stop the loop.</p> <p>Cyclic statement for (another model cycle) for (INITIALIZATION; Termination; Iteration) {body; // cycle body} initialization // Initialization // cycle condition ortholization // iterative, change cycle condition</p> <p>The §For statement is executed, first perform the initialization operation, then determine if the termination condition is met, if satisfied, the statement in the cyclic body is executed, and finally the iterative portion is executed. After completing a cycle, re-judgment the termination condition. § Initialization, termination, and iterative parts can be empty (but the semicolon cannot be provoked), and the three are empty, equivalent to an infinite loop. § Multiple operations can be performed using a comma statement in the initialization section and iterative portion. The comma statement is a comma-separated statement sequence. For (int i = 0, int J = 10; i <j; i , j -) {...}</p> <p>Program Transfer Related Statement Break In switch, the Break statement is used to terminate the execution of the Switch statement, so that the program starts from the first statement after the entire SWITCH statement. n In Java, you can add a label for each code block, and a code block is usually a piece of code enclosed in braces {}. The format of the marking is: BlockLabel: {CodeBlock;} NBREAK statement is the second usage of the NBREAK statement is to jump out of the block it specifies and execute at the first statement following the block. Break BlockLabel; Program Transfer Related Statements Continue §Continue Statement Used to end this loop, skipped in the following statement, then perform the determination of the termination condition to determine whether to continue cycling. For the for statement, before performing the determination of the termination condition, you must first execute iterative statements. Its format is: continue; § You can also use the Continue to jump to the outer loop indicated by the brackets, the format is Continue Outerlable;</p> <p>Program Transfer Related Statement RETURN § RETURN statement exits from the current method, returns to the statement that calls the method, and continues the execution of the next statement following the statement. Return statement has two formats: return expression; // When the method needs to return a type of data; // When the method's return type is VOID, § a single RETURN statement is placed in the middle of the method, because the compilation error is generated because The subsequent statements will not be executed. If you really need to exit, you can use the RETURN statement to embed certain statements (such as if-else), exit when all statements in the method are not implemented.</p> <p>Exception processing statement: try-catch-finally, throw When the program is designed, the incorrect generation is inevitable. How to handle errors? Have the error to Who deal? How do the program recover from errors? This is a problem that any programming language must face and solve. The Java language is incorrect through exception (Exception). We will introduce exceptions and processes in the sixth lecture.</p> <p>4. Java class definition specification JAVA is an object-oriented programming language with basic properties of object-oriented technology. Class is the main content of the expression of the face in Java, which is an important data type in Java, which is the basic element of the Java program. We will detail the definition of the class in the next lesson and the concepts related to the objects, packages, interfaces, etc.</p> <p>5. The Java array is in the Java language, an array is the simplest composite data type (reference data type). Array is a collection of order data. Each element in the array has the same data type, which can uniquely determine the elements in the array with a unified array name and subscript. An array has a one-dimensional number of groups and a multi-dimensional array. We will introduce in the later courses.</p> <p>6. Java Development Class Bank Composition Java provides a rich standard class to help program designers write programs more easily and easily, these standard classes consist of classes, mainly: java.lang java.awtjava.applet java.awt.Imagejava .awt.peer java.iojava.net Java.util In addition to java.lang, the remaining classes are not required by the Java language.</p> <p>1) Java.LANG This class contains classes that must be required when defined Java languages, which can access Java's inside. Any Java program will automatically introduce this package. The classes include: Object class: The most primitive, most important class in Java, each Java class is its subclass, which implements basic methods that must have each class. § Basic Type Packaging: Boolean, Character, Number, Double, Float, Integer, long. § String class: string class. § MATH class: Collection of mathematical functions. § Execute thread: class Thread, threadgroup, interface runable. § Exception, Error, Interface Throwable, Error. (1) Java.lang§ Run environment: You can access the external system environment by class Runtime and System. The two common functions of the System class are to access standard input / output streams and error flows, exiting the program. § Other classes: Interface Cloneable, runtime class, etc. (2) Java.applet Java Applet is a major charm of Java programming, and the Java.applet class package provides an APPLET's running mechanism and some ways to write Applets.</p> <p>(3) Java.awt This class is a unified interface of various window environments (AWT represents Abstract Windows Toolkit, which is an Abstractable Toolkit), which makes created, such as windows, menus, scroll bars, text districts, buttons, and complex The elements of the graphical user interface (GUI) such as selecting the box are very easy. (4) Java.awt.image package can load and filter bitmap images in a manner independent of the device. (5) java.awt.peer java.awt.peer is a collection of peer-to-peer objects of all AWT components. Each interface provides a basic method of machine-related methods, and AWT uses these methods to implement GUI, without having to care. Machine or operating system.</p> <p>(6) Java.io Java's input / output mode is fully based on the stream. Flow is one-way flow from one place to another, which can be attached to files, pipes, and communication links. Many streams defined in the Java.io class package are organized by inheritance, including some streams of files to access files on the local file system. (7) Java.NET Java.NET class package is used to complete the network-related features: URL, WWW connection, and more common Socket network communication. (8) Java.util Java.util class includes some practical classes and useful data structures, such as Dictionary, hashtable, stack, vectors, and enumeration (Enumeration) Wait. CHAP3. Java and object-oriented technology 1</p> <p>1, object-oriented concept</p> <p>The so-called object-oriented methodology is to enable us to analyze, design, and implement a system approach us to understand the method of understanding a system. Including: § Object-Oriented Analysis § Object-Oriented Design (OOD, Object-Oriented Design) § Object-Oriented Program Design (OOPL, Object-Oriented Program) Object-oriented technology mainly around the following Concept: object, abstract data type, class, type hierarchical (subclass), inheritance, polymorphism. § The object object has two levels of concepts. The objects in real life refers to an entity of a considerable world; and the object is a set of variables and related methods, where variables indicate the state of the object, the method indicates the behavior of the object. .</p> <p>The objects in real life can be abstract, mapped into objects in the program. Objects are described in the program, which is described by an abstract data type, which is called class.</p> <p>Class Car {Int Color_Number; Int Door_Number; Int Speed; Void Brake () {...} void spetedup () {...} void solutiondown () {...}}</p> <p>§ Class (Class) class is a "basic prototype" that describes the object, which defines the data that can be owned by a class of objects and can be completed. In object-oriented programming, classes are the basic unit of the program. Similar objects can be merged into the same class, just like the variables in the traditional language. The object in the program is an instance of the class, is a software unit, which is constructed of a set of structured data and a set of operations thereon.</p> <p>N variable: refers to the state of the object. n method: refers to the functional unit of the object. N Message Software Objects interacts and communicates by passing messages between each other, a message consists of three parts: Objects Accepting a message 2. Receive objects to take the method 3. The parameters required by the method</p> <p>n An example class hello {private string s; public void showString () {system.out.println (s);} public void change "{s = str;}} n In the program operation object is one of the class Example. n Create an object: hello obj = new hello (); N calling method: obj.showstring (); Why use the class with simple data types to represent the concept of the concept in the real world. Limitations. For example, INT data indicates a date concept, you need to use 3 variables: int Day, Month, Year; if you want to represent 2 people's birthday, use 6 variables: int mybirdhday, mybptermonth, mybpteryear; int Yourbpterday, YourBptermonth YourBpterhyear;</p> <p>There are not only variables in the class, but also the methods defined by the related operations. Packing the variables and methods in a class, you can hide the member variables, and the access to class members can be made by way, and the classes can be protected from illegal modification.</p> <p>Class birthdate {public int day, month, year; public int tomorrow () {...}} Birthdate mybirth, you.</p> <p>Birthdate date; Know the current date object, date the date of the second day: date.day = date.day 1; if Date.day is already 31, the results are illegal. You can define a member method tomorrow (), and ask the date object on the second day. When the external date is obtained, as long as the call: Date.Tomorrow (); N package package combines all components of the object, the package definition</p> <p>The program how to reference the data of the object, and the package actually uses the method to hide the data, control the degree of modification and access data for the class.</p> <p>The N sub-class class is a class defined as an expansion or correction of another class. § Inheritance is the method and variable defined in the parent class, just like they belong to the subclass itself.</p> <p>Class Car {Int Color_Number; Int Door_Number; INT Speed;</p> <p>Public void push_break () {...} public void add_oil () {...}}</p> <p>Class Trash_car extends car {double amount;</p> <p>PUBLIC VOID FILL_TRASH () {...}}</p> <p>The overlay of the n method redefines the method in the parent class in the subclass.</p> <p>Class Car {Int Color_Number; Int Door_Number; INT Speed;</p> <p>Public void push_break () {speed = 0;} public void add_oil () {...}} class trash_car extends car {Double Amount</p> <p>Public void fill_trash () {...} public void push_break () {speed = speed - 10;}}}} n method overload (polymorphism) at least two methods in the same class use the same name, but there is a different Parameters.</p> <p>2, class, methods and variables in Java</p> <p>Stringent definition and modifying word [Class modified word] Class class name [EXTENDS Parent Class Name] [IMPLEMENTS Interface Name List] {</p> <p>Variable definition and initialization;</p> <p>Method definition and method;</p> <p>}</p> <p>Class modified word: [public] [Abstract | Final] default method for Friendly</p> <p>§ Definition and modification of member variables</p> <p>[Variable Modification] Variable data type variable name 1, variable name 2 [= variable initial value] ...</p> <p>[public | protected | private] [static] [final] [transient] [volatile]</p> <p>The type of member variable can be any data type in Java, including simple types, classes, interfaces, arrays. The member variable in a class should be unique.</p> <p>§ Method and variable definition and modification word</p> <p>[Method Modified] Return Type Method Name (Parameters 1, Parameters 2, ...) [THROWS EXCEPTIONLIST] {... (statements;) // Method: Method}</p> <p>[public | protected | private] [static] [final | abstract] [native] [synchronized]</p> <p>The return type can be any Java data type, and when a method does not need to return a value, the return type is VOID. The type of parameters can be a simple data type, or the reference data type (array, class or interface), the parameter transfer method is the value transfer. The method is the implementation of the method. It includes a declaration of a local variable and all legal Java instructions. The role of the local variable is only inside the method. Class Cardemo {public static void main (string args []) {car democar = new car (); democar.set_number (3838); democar.show_number ();}} class car {int car_number;</p> <p>Void set_number (int car_num) {car_number = car_num;}</p> <p>Void show_number () {system.out.println ("My Car No. IS: car_number);}}</p> <p>§ The generation of object (1) object generates an object via the new operator; for example: car democar; democar = new car (); (2) The construction process of the object u is the object opening space, and the object's member variable is default Initialization; u The initialization of the member variable; ü Call the construction method.</p> <p>§ Object (3) The use of objects of objects is implemented by a reference type variable, including the member variables and methods of reference objects, and the access and method of access and method of variables can be implemented by operators. For example: birthdate date; int day; // Reference Date's member variable day date.tomorrow (); // call Date method Tomorrow ()</p> <p>§ Inheritance</p> <p>Class car {int car_number; void set_number (int car_num) {car_number = car_num;}</p> <p>Void show_number () {system.out.println ("My Car No. IS: car_number);}}</p> <p>class TrashCar extends Car {int capacity; void set_capacity (int trash_car_capacity) {capacity = trash_car_capacity;} void show_capacity () {System.out.println ( "My capacity is:" capacity);}}</p> <p>Class Cardemo {public static void main (string args []) {trashcar demotrashcar = new trashcar (); demotrashcar.set_number (4949); demotrashcar.show_number ();</p> <p>Demotrashcar.Set_capacity (20); demotrashcar.show_capacity ();}}</p> <p>Car is a parent class, trashcar is a subclass. The two methods in the trashcar are inherited, and two new methods are added. Inheritance is another basic feature of object-oriented programming language, and the code can be reused by inheritance. The class obtained by inheritance is subclass, the class being inherited is a parent class, and the parent class includes all classes that are directly or indirectly inherited. Multiple inheritance is not supported in Java. By adding an Extends clause in a class: Class SubClass Extends Superclass {...} This class is a subclass of java.lang.Object if the extends clause is default. Subclasses can inherit the visits in the parent class to set the member variables and methods of public, protected, default, but cannot inherit the member variables and methods of the access rights for private.</p> <p>N When choosing to inherit? A good experience: "B is a a a?" If so, let B make a subclass of A.</p> <p>§ Class method coverage is covered by redefining the methods existing in the parent class in the subclass.</p> <p>Class Car {Int Color_Number; Int Door_Number; INT Speed;</p> <p>Public void push_break () {speed = 0;} public void add_oil () {...}}</p> <p>Class Trash_car extends car {double amount;</p> <p>Public void fill_trash () {...} public void push_break () {speted = speed - 10;}}</p> <p>§ Calling method for the method of rewriting, the Java runtime system decides which method call to select according to the type of the instance of calling the method.</p> <p>Public class democar {public static void main (string args []) {car ACAR = new trash_car (); acar. push_break ();}}</p> <p>Here, the PUSH_BREAK () method in class trash_car will be called.</p> <p>§ Methods The principles that should follow (1) The override method cannot be more stringent access to the covered method. (2) Covering methods cannot produce more exceptions than covered methods.</p> <p>§ Overloading method of class methods means that multiple methods can enjoy the same name. However, the parameters of these methods must be different, or the number of parameters is different, or the parameter type is different. For example, to print different types of data, int, float, string, do not need to define different names: Printint (int); printfloat (float); PrintString (String). Using method overload, you only need to define a method name: println (), receive different parameters: println (int); println; println; string);</p> <p>§ The overloader of the polymorphic method is a polymorphism. In addition, the polymorphism can also refer to the place where the parent class object needs to be used in the program, can be replaced by sub-objects. For example: public class employee extends object {...} public class manager extends Employee {...}: Employee E = new manager (); // legal statement</p> <p>§ The hiding of the member variable can be hidden with the members variable: set the variable method setvariable (), get the variable method getVariable (). Class sample {int x; ... Void setx (int var) {x = var;} int getX () {return x;} ...</p> <p>§ The identification of the object state is in the Java language, providing an instance of operator instanceof to determine if an object belongs to a certain class.</p> <p>Public void method (EMPLOYEE E) {if (e instanceof manager) {... // do something as a manager} else if (e instanceof contractor) {... // do something as a contractor} else {... // do something else} }</p> <p>3, Java namespace and access rules</p> <p>N Each class has its own namespace, that is, the species and its methods and variables can know each other in a certain range, which can be used. For classes: NABSTRACT classes cannot directly produce objects that belong to this class; NFinal classes cannot be inherited by any other classes (security considerations); NPUBLIC classes can not only be used by other classes in the same package, other packages The class can also be used; the NFRIENDLY class can only be used by other classes in this package.</p> <p>n For member variables and members of the class, its application range can be limited by the application of certain access rights. Non-child private ★ default ★ ★ ★ PUBLIC ★ ★ ★ public ★ ★ ★ public ★ ★ ★ PUBLIC ★ ★ ★</p> <p>§Public: Any other class, the object can access the data of the variable as long as you can see this class, or use the method. § protected: The same class, the same package can be used. The class of different packages must be the subclass of such classes. § PRIVATE: No other class access and calls are allowed. § Friendly (there is no modified word front): The class that appears in the same package can directly use its data and methods. N The same variable name in the subclass is the same as the parent class, the variable of the parent class is covered.</p> <p>Class a class b extends a {{int DATA_A = 3; int DATA = 5;}} class c extends b {void print_out () {system.out.println ("DATA =" DATA_A); System.out.Println "A.data_a =" a.data_a); system.out.println ("b.data_a =" b.data_a);}}</p> <p>Class demo {public static void main (string args []) {c = new c (); c.Println_out ();}}</p> <p>§ This is until - Final§ Final Before class, the standard is that the class cannot be inherited. § Final prevented the method from being covered before the method. §Final defines a constant before the variable.</p> <p>§ These variables and methods that belong to the class --StaticStatic before variables or methods, indicating that they are class, called class methods (static methods) or class variables (static variables). If there is no Static modification, it is an example method and instance variable. Class variables share all instances</p> <p>Class abcd {char data; static int share_data;} Class demo {Abcd A, B, C, D;</p> <p>§ The survival of class variables does not depend on objects, which is equivalent to the role of global variables in the C language. Other classes can not be accessed by instantiating.</p> <p>Public class staticvar {public static int number = 5;} public class otherclass {public void method () {int x = staticvar.number;}}</p> <p>§ Class Method is equivalent to a global function in the C language, and other classes can be called to call them without instantiation.</p> <p>Public class generalfunction {public static int address {returnix x y;}} public class useGeneral {int a = 9; int b = 10; int c = generalfunction.addup A, b);}}</p> <p>§ The method in the same class can access member variables of the class; § A class method can only access its local variables.</p> <p>§ Incorrect reference class stating {string mystring = "hello"; public static void main (string args []) {system.out.println (mYString);}} error message: NonStatic Variable MyString Cannot Be Reference from A Static context "System.out.println (MyString);". Why isn't it correct: Only the object's method can access the variable of the object.</p> <p>Solution 1. Change the variable to class variable class staticerror {static string mystring = "hello"; public static void main (string args []) {system.out.println (mYString);}}</p> <p>2. Create a class of instances Class NostaticError {String MyString = "Hello"; public static void main (string args []) {NostaticError NoError; noerror = new NostaticError (); system.Out.println (noerror.mystring); }</p> <p>4, abstract classes, interfaces and packages in Java</p> <p>§ The abstraction method is modified with an abstract method to modify a class, which is called an abstract class; when a method is modified with Abstract, the method is called an abstract method. The abstract class must be inherited, the abstract method must be rewritten. Abstract classes cannot be instantiated directly. Therefore, it is generally an overclass of other classes and is just the opposite of the Final class. Abstract methods only need to be declared without implementation. Classes that define abstract methods must be an abstract class. Abstract Returntype AbstractMethod ([paramlist]);</p> <p>§ Two Class Circle and Rectangle, Complete Calculation Calculation Class Circle {Public Float R; Circle (Float R) {THIS.R = R; // This refers to "This object"} public float area ()} * r * r;}} Class Rectangle {public float width, height; rectangle (float w, float h) {width = W; // Height = H;} public float area ()} public float area () {Return Width * Height;}} It is assumed to have several Circle, as well as several Rectangle, I hope to calculate their total area, straightforward practice is to put them in two arrays, with two cycles, plus one addition, this practice It is not beautiful. If there are other shapes: Triangle, Ellipses, etc., the above method seems to be "cumbersome". We want to have a unified representation, such as using a array shape [], accept all shapes, then use: for (i = 0; i <shape.length; i ) {area_total = shape [i] .areAabstract Class Shape {Abstract float area ();} class circle extends shape {public float r; circle (float r) {this.r = r; // this refers to "this object"} public float area () {RETURN 3.14 * r * r;}}</p> <p>Class Rectangle Extends Shape {Public Float Width, Height; Rectangle (Float W, Float H) {width = W; // This is not required to "this" height = h;} public float area () {Return Width * height;}} The interface interface is a collection of method definitions and constant values. In essence, the interface is a special abstraction class, which only contains only constant and methods definitions, and there is no way to implement. ¨ The same behavior of the unrelated class can be achieved through the interface without considering the hierarchical relationship between these classes. ¨¨ The method of multiple classes need to be implemented through the interface can be specified. ¨ You can understand the interactive interface of the object through the interface without understanding the class corresponding to the object.</p> <p>Definition of the interface: [public] interface interface interface interfabename [extends superinterfacelist] {... // constant definition and method definition}</p> <p>Use the Implements clause to represent a class to use an interface. You can use the constant defined in the interface and all methods defined in the interface must be implemented. Multiple inheritage can be achieved by using an interface, that is, a class can implement multiple interfaces, separated by commas in the Implements clause. The role of the interface is similar to the abstraction, only the prototype is defined, and the content is not directly defined. The methods and variables in the interface must be public. Interface collection {int max_num = 100; void add (object obj); Object Find (Object Obj); int currentcount ();}</p> <p>Class Fifoqueue Implements Collection {Void Add (Object Obj) {...} Void delete (Object Obj) {...} Object Find (Object Obj) {...} int currentcount () {}} package (package) due to Java compilation Generate a zona file for each class, and the file name is the same as the class name, so the class of the same name may conflict. In order to solve this problem, Java provides a package to manage class space.</p> <p>The package is equivalent to the library function in other languages. Packing Java with a package statement to packet a class in a Java source file into a package. The Package statement is the first statement of the Java source file indicating the package where the classes defined in the file are indicated. (If this statement is available, it is specified as an ignorant package). Its format is: package pkg1 [.pkg2 [.pkg3 ...]]; Java compiler The package corresponds to the directory management, Package statement of the file system, is used. To specify the level of the directory. Package myclass.graphics; class square {...;} class circle {...;} Class Triangle {...;</p> <p>Package myclass.graphics; This statement specifies that files in this package are stored under directory Path / MyClass / Graphics. The root directory of the package level is determined by the environment variable classpath.</p> <p>In order to be able to use the classes already provided in Java, we need to introduce the required classes with the import statement. Import package1 [.package2 ...]. (ClassName | *); for example: import myclass.graphics. *; import java.io. *;</p> <p>Compilation and Generating Pack If you have defined packet P1 in program Test.java, you are compiled as follows: Javac -d DestPath Test.java, the compiler will automatically establish a subdirectory P1 in the DestPath directory and will be generated. Class files are placed under DestPath / P1. Destpath can be one of the environment variables ClassPath.</p> <p>5, the construction method of the object is a special method. Each class in Java has a constructor to initialize a new object of the class. The constructor has the same name as the class name, and does not return any data type. The system will be automatically executed when an object is generated. The content should be included in the constructor: § Define some initial value or memory configuration; § A class can have multiple construct methods (overload), which is executed according to the different parameters; § If the configuration method is defined in the program, Using an instance is a default constructor, it is a blanks that have no content. Public class Employee {Private String name; private int sales; public Employee (String n, int s) {name = n; salary = s;} public Employee (String n) {this (n, 0);} public employee () {This ("unknown");}} This object refers to your object, and its main role is to use this object as a parameter to transmit a method in other objects.</p> <p>Class thisclass {public static void main () {bank = new bank (); bank.someMethod (this);}} Class Circle {Int r; Circle (int R) {this.r = r;} public area () {RETURN R * R * 3.14;}} SUPERSUPER refers to the parent class of this object. SUPER can be used to reference (covered) methods in the parent class, (hidden) variables and constructors.</p> <p>Public class apple (int Price) {super (price); super.var = value; super.method;}}} The above program represents the use of the parent class to generate an instance, the Super must be a subclass The first statement of the constructor.</p> <p>Finalizer When collecting garbage collection, the Java runtime system automatically invokes the Finalize () method of the object to release system resources. This method must be declared as follows: protected void finalize () throws throwable {...} finalize () method is implemented in the user-defined class, it can be covered in the user-defined class, but generally Finally, you want to call the Finalize () method of the parent class to clear all the resources used by the object. Protected void finalize () throws throwable {... // Release the resources used in this class Super.Finalize ();</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-76332.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="76332" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.037</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'jUB0LmvRIwex_2B_2BCmryE4RiBqNuT8V6SWURUh1NTrvB6GNokqi3HDM67BKyYM2bYeQZe9OdPIJ8XJQJf3fzZTJg_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>