Zheng Zhiyuan's Java study notes

xiaoxiao2021-03-06  101

Zheng Zhiyuan's Java study notes

Zheng Zhiyuan CCB

1 Java origin

slightly

2 Java language overview

1. 3 principles for object-oriented programming: inheritance, polymorism, polymorephism

Package: One mechanism that bundles the code and its processing;

Inheritance: A process of obtaining an attribute of another object;

Polymorphism: an interface, a variety of methods.

2. System.out.println ("DFJDFJDF");

System.out.print ("DFDFDFDF");

These two ways of writing are basically the same, but the print does not change.

3. Basic Word: WhiteSpace Identifiers Message Constant (Comments) Delivery (Separators) Java Keyword Java Category Library

3 data type, variable, array

1. Java language is a strong type language, Java defines 8 simple data types: Byte Short Int Long Char float double boolean

2. If a data type accounts for 8 bits, his range is - (2 of the 7th side) to 2 seven times - 1, a total of 2 8 times (don't forget 0), which is the highest as a symbolic bit, Is 1 is negative.

Among them: (2 8th party -1) equal to 2 0 times 2 1 ... 2 of the 7th

Therefore, if the address is 00000000 in the IP address, the representative can have 256 addresses, 0 times 2 1 square ... 2 points = 255, but don't forget 0! ! !

3. The standard ASCII character set ranges from 0 to 127 (a total of 2, because the highest bit is useless), the extended ASCII character set range is 0 ~ 255 (a total of 2 8 times)

Unicode characters set up 16 bits, range: 0 ~ 65535 (a total of 2 16 times)

4. System.out.println ("THE VALUE IS" (10> 9)); result is true, 10> 9 plus parentheses, because is priority than ">"

System.out.println ("10> 9"); result is 10> 9

5. Octal ------ 8 Enter, front plus 0

HEXADECIMAL ------ 16, before adding 0X or 0X

6. The floating point literal in Java is default double precision, accounting for 64 digits.

1234.333F (ORF) --------- Float

1234.343434D (OR D) ------- Double

So: float m = 20.3 will compile errors, should be written as float m = (float) 20.3

7. Automatic type conversion:

The following two conditions are met: these two types are compatible; the range of the purpose type of the purpose is large.

Mandatory type conversion:

The conversion between the two incompatible types, the format is: (target-type) value, for example, turning the shaping into byte type, if the value of the shaped value exceeds the value range of the byte, the transformation value is pair 256 touch. BYTE B; INT i = 300; B = (byte) i; then the value of B is 44. For example, the step of enforcing 323.234 to BYTE: Remove the number of decimal points to 323, and 323% 256 is executed 67.

8. The automatic type is improved, in the expression, Byte and Short are automatically enhanced to INT type

E.g:

BYTE B = 50;

B = b * 2; // Compile will be wrong! Because B * 2 is plastic

Should be written as

B = (BYTE) (B * 2) // The priority of parentheses is greater than *, so B * 2 should be added parentheses

Another example:

Short mm = (short) 0x8000; // This (short) must also be written, otherwise compiling an error! ! !

9. Array, statement format:

Int array [] = new int [3];

or

Int arch [];

Array = New Int [3];

//initialization

Array [0] = 1;

Array [1] = 2;

Array [2] = 3;

or

INT Array [] = {1, 2, 3}; // Automatically allocate memory without NEW operator

Note: [] It cannot be written within the length, otherwise compiling an error! ! !

In addition, Java performs array crossed inspection, and C / C is not

Multidimensional Arrays:

INT DSHUZU [] [] = new int [2] [3];

initialization

DShuzu [0] [0] = 1; ...............

Or int dshuzu [] [] = {

{12, 13, 14},

{20, 21, 22}

}; // [] cannot be written within length, otherwise compiling an error! ! !

You can allocate memory first, and the second dimension is manually allocated. E.g:

INT DSHUZU [] [] = new int [3] [];

DShuzu [0] = new int [1];

DShuzu [1] = new int [2];

DShuzu [2] = new int [3];

The second dimension is not equal, the legend:

DShuzu [0] [0]

DShuzu [1] [0] dshuzu [1] [1]

DShuzu [2] [0] DShuzu [2] [1] dshuzu [2] [2]

An additional array declaration method:

Int [] mm = new int [12];

int [] [] nn = new int [3] [4];

In the Java in the Java, the array is used as an object. An array has an example variable Length, which is stored in the number of elements that arrays can contain.

E.g:

Char arr [] = new char [10]; / / regardless of the array, or an array of plastic, the number of elements is 10, the subscript is from 0-9

Arr.length; // His value is 10

INT Arr1 [20] = {1, 3, 4, 5};

Arr1.length // His value is 20

Char str [] [] = new char [2] [3] // This two-dimensional array of Length is 2. First dimensional length

10. The variables in the middle declared in Java must be assigned, although it has its own default. E.g:

INT I;

System.out.println (i); // Compiling will be wrong, prompt i does not initialize, resolve: int i = 0; but instance variables do not exist.

4 operator

Four major operators: arithmetic operator, bit operation, relational operation, logical operation

There is also a comparison operator (InstanceOf)

4.1 Arithmetic Operation Symbol

The arithmetic operator cannot be used on Boolean, but can be used on the char, because the CHAR type in Java is a subset of the int type.

"/" For integers, the remainder will be went. For example: INT i = 6/4; result is 1.

The% operator can also be used in floating point numbers (not allowed in C / C ) for example:

The result of 42.25% 10 is 2.25

Note the difference between incremental decrementing operations M and M

The value of m and M remain synchronized, and the value of M is ratio M small 1. For example INT m = 0;

m; // then the value of M is 1, M expression value is also 1

M ; // then the value of m expression value is 0

There is an example:

INT i = 100; int J = 200;

While ( i <--j); // Empty cycle body, I is greater than or equal to j, end

System.out.println (": i is" i); // Survere the intermediate value of i and j 150

Arithmetic assignment operation, for example: A = 4; equivalent to A = a 4;

4.2 BitWise Operators

Directly operate the integer type bit, including: Byte Short Int Long Char.

Understand the inverse, complement. The negative 2 branch representation is: Do 1 after the original code is reversed.

The integer is symbolic, (except for char), so use their highest bit to represent symbolic bits.

Note: When the BYTE and SHORT are shifted (left or right or right), Byte and Short are automatically raised to the INT type. Perform the shift operation. If Byte and Short are negative, it is to say that the symbol is also expanded, and the high position is filled with 1, then do the shift!

E.g:

BYTE B = 01000000;

INT I;

i = B << 2;

/ / The result is 256, 2 to 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

B = (Byte) (B << 2); / / The result is 0, Byte is only 8 bits, the high is truncated

For example: byte b = 11111111; // decimal is -1

B = (Byte) (B << 2);

// Change to 11111111 11111111 11111111 11111100, 10 is -4

B = (BYTE) (B >> 2);

// Change to 1111111111 11111111 11111111 11111111, 10 is -1

B = (BYTE) (B >>> 2);

/ / Change to 0011111111 11111111 11111111 11111111, b or -1, because B first expanded to int

Note: When left (<<), if the 1 moves 1 moves into the high (31 or 63), it will become negative.

High shift, low 补 0

Right shift calculation (>>): low shifts, highlights the original high value. No symbol right shift (>>>): low shift, high level 0 padding.

Note: Because Short and Byte are always extended to 32 bits, symbol bit extensions and movements always occur at 32 and 64.

Master the bit assignment operator, for example: a = a >> 4; equivalent to A >> = 4;

A ^ = b; equivalent to a = a ^ b;

4.3 Relationship Operators

==> <<=> =! =

The result of the relationship is Boolean, only True and False, unlike C / C , non-0 is true, 0 is False.

Boolean flag = a

4.4 Boolean logic operator

The number of arithmeters of the Boolean logic can only be a Boolean, and the result is also the Boolean type.

note:

Standard logic and (&) and logic or (|) calculate the second expression regardless of the first expression of True or False. E.g:

IF (c == 0 | E <100) D = 12; // Whether the C is equal to 0, e is all increed.

Short-circuit AND (&&) and short-circuit OR (||):

A && B, when A is False, does not calculate the value of B and return false directly; when A is TRUE, the value of B is calculated.

A || b, when A is True, the value of B is not calculated and returned directly; when A is False, the value of B is calculated.

4.5 Assignment Operator (=)

INT X, Y, Z;

X = y = z = 100; // Allows to assign a series of variables

4.6? Operator

Ternary operators often use to replace the IF-ELSE statement. format:

Expression1? Expression2: Expression3

// Expression1 is a Boolean expression, Expression2 and Expression3 are any type of expression other than the Void type, and their types must be the same.

E.g:

Rado = denom == 0? 0: Num / denom;

// If Denom is equal to 0? The value of the expression is 0, otherwise Num / Denom. Last? The value of the expression is assigned to Rado

4.7 Priority of the operator

Master the priority of the operator. Appropriate use () can improve the readability of the program, clarify the meaning, and not to reduce the running speed of the program.

5 program control statement

Java program control statement is divided into: Selection, Repeated, Jump (JUMP)

5.1 Selection statement of Java

Java supports two selection statements: if statements and Switch statements.

5.1.1 IF conditional branch sentence

IF (condition) // condition can only be Boolean

STATEMENT;

Else IF (condition)

STATEMENT;

Else IF (condition)

STATEMENT;

...............

Else

STATEMENT;

5.1.2switch multiple-way branch sentence

Switch (expression) {

Case Value1: Statement;

Break;

Case Value2:

STATEMENT;

Break;

..............

DEFAULT:

STATEMENT;

}

// wherein Expression must be byte, short, int or char type, each of the Value, must be a constant compatible with the expression type

BREAK is used to jump out of the entire Switch statement. If BREAK is omitted, each statement is traversed, and the condition is executed until the end of Switch or Break is encountered.

E.g:

Switch (expression) {

Case Value1:

Case Value2:

Case Value3:

STATEMENT;

Break;

Case Value4:

Case Value5:

STATEMENT;

Break;

..............

DEFAULT:

STATEMENT;

}

Note: The Switch statement can only test equal conditions, while if IF can calculate any type of Boolean expression.

There are no two identical Case constants in the same Switch statement, except for the external CASE constant of nested Switch and internal CASE constants.

The Switch statement is usually more effective than if the IF statement.

5.2 cycle statement

Including: While Do While for

5.2.1 While cycle

Format: while (condition) {

// body of loop

} // Condition is a Boolean expression

The empty cycle is legal in Java.

The empty statement is only one semicolon (;) statement. E.g;

INT i = 100; int J = 200;

While ( i <--j) // I and I Synchronize

; //; Can be connected to the While statement ( i <--j);

System.out.println ("i =" i);

Of course, the example above can be written as:

INT i = 100; int J = 200;

While (i

I ; J-;

}

System.out.println ("i =" i);

5.2.2 DO-While Cycle

Format: do {

// body of loop

} while (condition); // Do not miss it;

The cycle is at least once.

example:

INT n = 10;

Do {

System.out.println ("n =" n);

n--;

} while (n> 0);

It can be written as follows, more efficient.

INT n = 10;

Do {

System.out.println ("n =" n);

} while (--N> 0); // - n is synchronized with the value of n

5.2.3 for loop

Format: for (Initialization; Condition; ip) {

// body of loop

}

// If only one statement needs to be repeated, {} is not necessary. The initialization expression is only executed once. For example, I = 0 only once in FOR (i = 0; i <10; i )! ! ! Declare a loop control variable in the FOR cycle. E.g:

For (int i = 0; i <10; i ) {

..........

} // i 's scope of the field is over after the FOR cycle is executed.

Use "," in the for loop. E.g:

For (a = 1, b = 4; a

Note: In Java, the comma is just a separator, only for the for loop! ! !

For (;;) {

...... ..

} // This will be an infinite loop

Master cycle nest

5.3 jump statement

Java supports three kinds of jumping statements: Break Continue Return

5.3.1 BREAK statement

Role: 1, in Switch, terminate a statement sequence

2. Exit a cycle

3. As an advanced "goto" statement

Note: Break in the Switch statement affects the Switch, without affecting any loop;

The internal cycle Break only terminates the cycle, and the external cycle is not affected.

Use Break as a form of goto (not limited to loop), the maximum use is to jump out of the multi-layer cycle. Format: Break label; example:

Public static void main (strings [] args

{

Label1: {

Label2: {

For (i = 0; i <10; i )

{

IF (i == 5) Break Label1; // Execute the jump out of Label1, start execution at the end of Label1

}

}

System.out.println ("not arrival here"); // is not executed

}

System.out.println ("Hello! Arrive HERE"); // is executed

}

Program last output: Hello! Arrivel Here

Another example:

Outer: for (int m = 0; M <3; M ) // The range of loops is fixed, so the Label for looping may not bring {}. Of course, you can also include more statements with {}. The key is to pay attention to the range of Label.

{

System.out.println ("Pass" M);

For (int i = 0; i <50; i ) {

IF (i == 10) Break Outer; // If only Break is written; then jumps out of the loop, starting from the end of the loop.

System.out.println ("i =" i);

}

System.out.Println ("Not Execute Me");

}

Sytem.out.println ("I am EXECUTED");

Note: If the Label1 does not include Break, Break Label1 is illegally, not compiled. E.g:

Label1 {

...............

}

For (i = 0; i <10; i ) {

IF (i == 5) BREAK Label1; // Error! ! ! Because Label1 does not include Break

}

5.3.2 Master the usage of Continue. 5.3.3 RETURN statement. Will study in the subsequent chapter.

The following example will compile an error, prompt: Unreachable Statement Because the compiler knows the println statement will never be executed. This also exists in the C language, but only Warning is proposed when compiling.

Class test {

Public static void main (String [] args) {

INT m = 100;

Return;

System.out.println ("M IS" M);

}

}

The solution is to add a TRUE value in front of the Return to be cheated, such as:

Boolean flag = true;

IF (Flag) Return;

6 introduction class

Class is the core and essence of Java.

6.1 foundation

Category is a logical construction that creates a class equivalent to creating a new data type.

Objects have physical authenticity, that is, objects occupy memory space

Objects are an instance of the class (Instance), so it is often used frequently and Object.

Categories include member variables and members. Member variables include instance variables and static variables.

6.2 Statement Object

See "Java2 Reference Daquan"

Dynamic allocation memory is allocated at runtime, implemented by the New operator.

Class declarations just create a template (or type description) and do not create an actual object.

6.3 Assignment to the object reference variable

Object b1 = new object ();

The address value of Object B2 = B1; // B2 and B1 is equal to the same object.

At this time, B1 and B2 references the same object, not the copy of the object. Changes to objects via variable B2 will affect the objects corresponding to B1.

B1 = NULL; // Here B1 is set to be empty, but B2 is still pointing to the original object.

Pointer equivalent to C.

6.4 method

There are two members of the access class:

1. Access to the interior code

2. Access to the external code

When an instance variable is not accessed by some code of the instance variable, it must be accessed through the object to add an operator. However, when an instance variable is defined for partial code access of the class of the variable, the variable can be directly referenced. The same rules apply to methods.

There must be a return value when writing methods, and does not return to write void. (Constructor exceptions.)

Otherwise, when compiling: invalid method declaration; returniting

E.g:

Class Box {

Double width;

Double height;

Double depth;

Double volume () {

Return Width * Height * Depth // No object plus point number

}

Void Setdim (Double W, Double H, Double D) {

Width = W;

Height = h;

DEPTH = D;

}

}

// A good Java program, its instance variable should only be accessed by the internal method, and should not access it directly. Object obj = new object (); obj.var1 = 10; this is not good. Such as: VB.

Class demo {

Public static void main (String [] args) {

Box mybox = new box ();

Double Vol;

MyBox.Setdim (12, 13, 14);

Vol = mybox.volume ();

System.out.println ("Volume IS" VOL);

}

}

Note: The following is different from the parameter and parameters (argument)

The argument is a variable defined by the method. When the method is called, he receives a value. For example, W, H, D in SETDIM (Double W, Double H, Double D) is the argument

When a method is called, the parameter is passed to the value of the method. For example, SETDIM (12, 13, 14) transmits 12, 13, 14 as parameters, and the variables W, H, D receive them.

6.5 Constructor

The constructor is in the same name. After the object is created, the constructor is automatically called before the New operator is completed. The constructor has no return value, even if the VOID type is not returned. His task is to initialize the internal state of an object, so that the instance variable can be fully initialized, which can be called immediately immediately.

If you do not explicitly define a constructor, Java will create a default constructor for this class, which initiates instance variables into zero.

In the example in 6.4, Void SetDim is changed to Box (Double W, Double H, Double D). Note: Box must be with the same name, case sensitive! ! !

6.6this ​​keyword

The objects reference the method are referenced in the method. Using this is redundant, but it is completely correct. He is more useful in 6.6.1.

E.g:

Box (Double W, Double H, Double D) {

THIS.WIDTH = W;

THIS.HEIGHT = H;

THIS.DEPTH = D;

}

6.6.1 Hidden instance variables

In the same method, defining two renowned local variables are illegal in Java. but,

The variables of the variables and methods within the method can be the same as the name of the instance variable of the class. At this time, the instance variable name is hidden, so you have to access the instance variable of the same name with the THIS keyword.

E.g:

Box (Double Width, Double Height, Double DePth) {

THIS.WIDTH = Width;

THISHEIGHT = HEIGHT;

THIS.DEPTH = DEPTH;

} // Width Height Depth is an instance variable

6.7 Garbage Collection

Java automatically handles reassign memory. The garbage collection is only occasionally happening in the program. For most programs, it is not necessary to consider garbage collection problems.

6.8finalize () method

When you have an object, you need to explicitly complete some operations, such as an object processed non-Java resource, such as a file handle or Windows character font, then ensure that these resources are released before the object is revoked.

The Finalize () method is just called before garbage collection. However, when an object beyond his scope, Finalize () is not called. We don't know when, or even finalize () is called, so it is best to release system resources used by other methods, do not rely on the Finalize method.

6.9 a stack class

7 Further research methods and classes

7.1 Method Overloaded (Method Overloaded)

Method Overload is a way to achieve polymorphism, determine the version of the overload method by the type or quantity of the parameters, although each overload method can have different return types, but the return type is not enough to distinguish Which method is. 7.1.1 Technical Function Overload

Multiple constructors can be overrunted. You can also construct one other as Box

Box () {

Width = 1;

HEIGHT = 1;

DEPTH = 1;

} // This is more convenient, you can use it when you just want to create an instance variable, you don't have to enter parameters.

7.2 Use the object as a parameter

See "Java Reference Daquan 114"

The most common use of object parameters involves constructor, constructs a new object, so that its initial state is the same as an existing object.

E.g:

Box (Box Obj) {

Width = Obj.width;

Height = Obj.height;

DEPTH = Obj.depth;

}

// Key: As the name of the name as the data type, just like Java's built-in type. Parameters passing to OBJ are naturally created previously. And the pointer parameters of C are similar, for example

Function: Kill_Blank_all (Char * STR), you don't have to assign memory to STR in the function body, because before calling this function, the string memory as a parameter has been assigned.

for example:

Box Box1 = New Box (12, 13, 14); // Box1 is declared and allocated and initialized.

Box clone_box = new box (Box1); // Box1 is an object

7.3 How is the parameter passed?

1. Copy the parameter value by value transfer (Call-by-value) //

2. Call-by-reference) // Point to the same object

Note: When a simple type is passed to a method, use the value transfer. Object transfer is passed by reference.

In fact, an object reference is transmitted, the reference itself is passed, but because the value passed points to an object, the value of the value is still pointing to the same object.

7.4 Return to the object

The method can return any type of data, including the type of class you created. E.g;

Box test_meth () {

Box

Box1

= New Box (12, 13, 14);

Return Box1;

} // Blue Box is the return type, and the return pointer of C is a reference.

The class ratio of the C / C character pointer:

Box

Box1

= New box ();

Char * str0 = "compare to c";

Box Box3; // Declare a Box type reference, but which is not allocated, with char * STR;

Box3 = Box1.test_meth (); // will reference the object to a already existing object. STR = STR0;

Example of a database operation:

ResultSet res = conn.execute ("Select * from table"); // Database object method EXECUT's return type is an object: resultSet. So, some places don't have to explicitly use New to create reference objects.

7.5 Recursive (Recursion)

Recursive is that the method is allowed to call itself, and its typical example is the number of all numbers between 1 --- n. Refer to Daquan 118.

Recurns, iterates each having its own advantages.

7.6 Introduction Access Control

If the other parts of the program can be circumvented by wraping a class (interface) and directly accessing the variables of the class, the package is not good. It can be controlled by accessing the indicator (Access Specifier). Extreme practice is to set all the members variables to Private, which can only be accessed by class methods. VB is not good, many attributes can be accessed directly.

Mainly include Public Private Protected default access level (in the package public)

The Private member in the class is private, and you cannot access all code outside of the class, including subclasses.

The main () method is always modified by the public indicator because he is to be called by Java runtime. If there is no public, compile the prompt: Main Method Not public

7.7; Understanding Static

If a member is declared as Static, he can be accessed before his class object is created, and do not have to reference any object. The most common example is the main () method, because main () must be called at the beginning of the program, so he is declared as static. If there is no STATIC, compile the prompt:

Exception in thread "main" java.lang.nosuchmethoderror: main

See Daquan 125 pages

Class variable: All instances share a variable.

Class method:

1. Can only call other static methods directly

2. You can only call the Static variable (data) directly, call any instance variables. However, instance variables can be accessed by declaring the objects.

3. This and super will not be referenced in any way. Because they represent the object.

4. Class methods can have their own arguments.

Some of the above points apply to the main function, go to 8.1

Call method:

Class_name.variable

Class_name.method ()

Static block declaration method:

STATIC {

System.out.Println ("this is a static block");

}

Calling a class method is: First, the Static variable of its class is initialized once

Furthermore, the Static block is only initialized once, the latter, class method is executed.

E.g:

Class userStatic {

Static int i = 3;

Static Int J;

Static void meth (int x) {

System.out.println ("x =" x);

System.out.println ("i =" i);

System.out.println ("j =" j);

}

STATIC {

System.out.println ("Static Block Initialized");

B = a * 4;

}

Public void main (string [] args) {

Meth (42);

}

}

The output is:

Static Block Initialize

X = 42

i = 3;

J = 12

7.8 Introduction Final

Variables are declared for Final, which is constant, similar to consts in C / C . E.g:

Final INT flag = 1;

Final variables are generally capitalized, and in the examples do not account for memory, substantially constants. Although this, it is still necessary to instantiate the class to access, not like Static.

The other two functions of Final are inherited: 1. The Final method prevents the subclass from coverage, but can be accessed in other classes.

2. Final class can prevent inheritance.

7.9 略

7.10 Introduction Nested and Internal Class

The classes defined in another class are Nested classes.

Two types of nested classes:

1. The nesting class of the Static identifier is added. He cannot directly reference members of the encirclement, only through objects to access members of the encirclement. Therefore, this nested class is rarely used.

2. Inner Class: Nested classes of the Static identifier in front.

Class B is defined within class a, then B is known, but not known as A. Any code outside class A attempts to instantiate class B, compile errors, but the code inside class A can be instantiated B.

Nested classes can directly reference members variables or methods of nested its classes, including Private, but encirclement categories cannot be directly referenced but can access the members variables and methods of nested classes through objects.

Note: It is not appropriate to use "Can I access" here.

The internal class and the external class of the external class also has within or within the method of the external class.

If it belongs to the latter, this internal class can not only directly reference the member variables of the external class, but also directly reference the local variables.

E.g:

Class Outer {

INT i = 10;

Class inner {

Void in_meth () {

System.out.println ("i is" i); / / directly call the encapsulated variable

}

}

Void out_meth () {

Inner in1 = new inner (); // Encircle-enclose an instantiated internal class

IN1.IN_METH ();

}

}

Experience: In fact, an internal class, a member of the included class is just a range issue, one in the range of {}. This role is over, and the life of the member is over.

It can also be understood from the two ways of access. Class code access (direct reference) and class external code access (Object Add Type Access): Internal class is a class code for the encirclement class, the code surrounded by the class is an external code for internal classes.

Let's take a look at a C language program.

Main ()

{

INT i = 1000;

INT J = 2000;

{/ 注意意 作

INT i = 23; // will temporarily cover 1000

INT m = 50;

Printf ("% d / n", i); / / result is 23

Printf ("% d / n", j); / / result is 2000, explaining the variables of the gesture outside the scope directly

Printf ("% d / n", m); / / result is 50

} // The role field ends here

Printf ("% d / n", i); // The result is 1000, 23 has been released.

Printf ("% d / n", m); // compile period error. M has died. Note Variables in the scope cannot be directly referenced.

}

Internal classes are generally not used, but it is helpful when processing applets. There is an anonymous inner class, an internal class without a name. See Chapter 20 for details.

7.11String class

Every string we created is an object of the String type.

String type object is unmodolate, if you want to change, you can create a new string, which contains the modified string.

StringBuffer type strings can be changed.

Connection string operator: , Note: It cannot be used for any other type

String class method:

Boolean Equals (String Object) // Checks if the contents of the two string references are equal

INT length () // The length of the string is obtained, and the Java string has no '/ 0'.

Char charat (int index) // gets the character string specifies the index. Start from 0.

String array

String str [] = {"abc", "cde", "mnodf"}

7.12 command line parameters

Public static void main (string [] args);

The command line parameter exists in the args array, args.length is the number of parameters. 0 is not parameters, unlike the command itself as the first parameter, no matter how Argc is at least 1. C command line parameters are implemented by the CHAR type pointer

Java and C / C : Command line parameters are passed in the form of a string. You must handle strings into the types required in the program.

For example: The first parameter is 8, then args [0] = "8", in fact, the string object, the program is integrated, and you must convert. Another example:

C: / Java Command M, then args [0] = "m", m is a string object, not a simple type ---- character. The method is: CHAR C; C = Args [0] .Charat (0).

Changed to C language, actually args [1] = "m / 0", if you want to give it to Char C; then only c = args [1] [0]; it is correct. Don't forget that Args [0] in the C language is equal to the command itself.

8 inheritance (inheritance)

Create a class of class hierarchy.

Vocabulary: Superclass Super Subclass Subclass

format:

Class Subclass-Name Extends Superclass-Name {

// body of class

} // A subclass can only have a superclass (hyperclass is not exceptional), which is different from C to inherit multiple basic classes.

// No class can be his own superclass.

8.1 Inherited Foundation

Subclasses include all members of the superclass, can directly reference these members because they are inherited for their own. But you cannot access the Private member, but you can override the OR overload private variables and methods. The super-class Static method cannot be covered by the subclass, but overload (unless the method of the subclass is also modified).

Experience STATIC, for example:

Class superc {

INT m = 1000;

Void superfun () {

System.out.println ("This Is A Super Class");

}

}

Class Subc Extends Superc {

Public static void main (String [] args) {

System.out.println ("My M IS" M);

Fun ();

}

}

// The above two sentences seem to be correct, because the subclasses completely have members of the parent class, however, important main main () method is modified by static, only call class variables and class methods. Because M is not a Static variable, it is wrong, prompt: Non-Static Variable M Cannot Be Reference from a static context

Workaround: Put the public static void main () in a class, call the member through the SUBC class. Therefore, when writing the Java program, the class of the main () method is generally unfained. E.g:

Class Subc Extends Superc {

INT n = 19;

Int subfun () {

Superfun (); // Direct reference

RETURN M N;

}

}

Class demo {

Public static void main (String [] args) {

Subc Subc1 = New Subc ();

System.out.println (SUBC1.M);

Subc1.superfun ();

Subc1.subfun ();

}

}

The superclass reference variable can be assigned by any reference to the subclass of the superclass. However, you can only access the member part of the superclass defined. If the method is overridden: The type of reference variable determines the member variable called who is called; the type of the reference object determines the member method of the call. That is, the same name method calls subclasses, and the same name variable calls superclars. This is called a super class reference variable reference subclass object.

E.g:

Class Super

{

INT i = 100;

Void fun () {

System.out.println ("super")

}

}

Class Sub Extends Super {

INT m = 1;

INT i = 2; // covers the super class I

Void fun () {// overrides the superclass method FUN.

System.out.println ("Sub")

}

}

Super S1;

SUB S2 = New Sub ();

S1 = S2; OR S1 = New SUB ();

System.out.println (S1.I) // Output 100

System.out.println (S1.Fun ()) // Output SUB

System.out.pritnln (S1.M) // Compile error, prompt CAN NOT BE Applied to ... .. Because there is no definition in superclars

8.2 Using Super

1. Use Super Call the superclass constructor.

Format: super (parameter-list)

Note: The Super function must be the first statement of the subclass constructor. If it is not explicitly written, Java will call Super () by default. Moreover, Super () is always the most close to the subclass of the subclass of superclass in multi-level inheritance. The call sequence of the constructor is called in the derived order.

For example: B is a subclass of A. Then when the constructor is called, if it is not explicitly indicated, the configuration function A () A () is called by default. At this time, if there is a constructor with parameters in A, it is compiled. Error. If there is no explicit defining constructor in A, it is correct. Note If a (parameter) is defined, no A () said, unless you are defined!

1. The same member name hidden in the super-class member name quilt, that is, members coverage

Format: super.member

Only the return type and method name, the parameter is exactly matched, otherwise it will become a method to overload the experience: Good programming habits, from the superclass to select the appropriate constructor, display in the constructor of the subclass Calling Super (Argement) unless the hyperclass does not have an explicit defining constructor.

8.3 Creating a multi-level class level

B inheritance A, C inherited B

8.6 Inheritance and Running Polymorphism

Implemented by assigning a subclass of objects to a category reference variable. E.g:

Super class Super, he has a method Callme (), outputs I am super on the console.

It has two subclasses SUB1 and SUB2, which covers the CallMe () method of Super, outputs I am Sub1 and I am Sub2.

Super S0 = New Super ();

SUB1 S1 = New Sub1 ();

Super ss;

SS = S0;

ss.callme (); / / result is I am super

SS = S1;

ss.callme () / / The result is I am Sub1

SS = New Sub2 ();

ss.callme () / / result is I am Sub2

Function name, parameter, return value, and a series of related objects, but the result of returning is different, this runtime polymorphism is only available to the subclass reference variables overwritten by inheritance. There are also interfaces in Chapter 9.

Method coverage is a special case of method overload.

8.7 Use abstract class

Just define a universal format for a subsidiary shared.

Abstract method: abstract type method-name (parameter-list); there is no function body, do not miss the semicolon

Abstract class Abstract Class class-name {..........}

Any class containing one or more abstract methods must be declared as an abstract class. Abstract classes cannot be unsearched through the New operator, but can create object references (categorous type reference variables), point to subclays to implement runtime polymorphism.

Note: The constructor and static methods cannot be defined as Abstract. The subclass of abstract classes must cover (rather than overload) to implement abstract methods in superclasses, otherwise the subclass must be declared as Abstract.

8.8 Using Final

The three roles of the final modifier, the previous existed: 1. Declare constant; 2. In the inheritance, the method is prevented from being covered (unless the method of the subclass is also modified) (but the final method can be overloaded); 3. In inheritance, all methods (excluding member variables) are all finaled in inheritance, prevention, and classes are declared as Final.

Final methods can improve program performance, and the compiler can bundle it. Early binding. See 7.8

8.9 Object Class

The Object class is a superclass of all other classes, so an object type reference variable can reference any class of objects, including an array.

Several methods of the Object class:

Object Clone () // Create a copy of an object

Boolean Equals (Object Object) // Declaration if the content of the object is equal

Calss getClass () // Get a class of an object (that is, from that class)

String toString () / / Returns a string of the object, but the method is automatically called when the object is output with the Println () method, for example: system.out.println (object); actually system.out.println (Object .tostring ()). Many classes are overloaded. 9 packs and interfaces

Two innovative features of Java: package and interface.

Package: It is a class of containers, and is stored in a hierarchical manner, which is a space used to save the class name. The package is both a naming mechanism and a visibility control mechanism.

Interface: Interface does not define any implementation. Categories can implement multiple interfaces, and the class can only inherit an overlay (abstract class or other).

9.1 package

Java uses the file system directory to store the package, the directory name must be strictly matched with the package name. E.g:

Package com.sun.zzy;

Class test {

// body of class

}

Then the directory is: com / sun / zzy (windows); COM / Sun / Zzy (UNIX)

All classes belonging to the package must be stored in this biller.

Execute class: java com.sun.zzy.test must be package name plus class name

ClassPath: The default is. Before working directory. Suppose the above directory structure is under C: / Myjava, the classpath should be:.; C: / myjava; ............., Such com.sun.zzy.test can be executed everywhere, otherwise you can only be in C: / Myjava The following is performed because it is searched according to the directory structure.

9.2 Access Protection

Access level of class: only 2

By default: only accessible by the same bag

PUBLIC: Can be accessed by any code

Access level for class members:

Private member

Default member

Protected member

Public

Visible in the same class

Yes

Yes

Yes

Yes

Subcador in the same bag visible

no

Yes

Yes

Yes

Non-non-child class

no

Yes

Yes

Yes

Subclasses in different packages

no

no

Yes

Yes

Non-non-non-non-non-subclassics in different packages

no

no

no

Yes

9.3 introduction package

format:

Import java.util.date;

Import java.io. *;

* In order to introduce the entire package, this form will increase compilation time, but the size, runtime, performance of the class has no effect.

The compiler implicitly introduces the basic language function package java.lang: import java.lang. *;

Note: When a package is introduced, it is only available in the packet to the PUBLIC class to be available in the introduction code.

9.4 Interface (Interface)

It is necessary to do anything, regardless of how you do it. Implement "an interface, multiple methods"

format:

Access-modifier interface interface interface-name {

Return-Type Method1-Name (parameter-list);

Return-Type Method1-Name (parameter-list);

TYPE FINAL-VAR1NAME;

..........

} // All methods in the interface do not have a method, and it is ended.

Access-Modifier: Only public and default.

The variable in the interface is finafter, which is a constant. If the interface is modified by public, all of her variables and methods are public. E.g:

Interface sharconst {

INT NO = 0;

Int yes = 1;

Int later = 8;

}

Class quer imports shareconst {

Int fun () {

Return NO;

}

}

This form of the variable in the interface is like the #define constant created with head files in c.

Note: A class can implement multiple interfaces, and the way to implement the interface must be declared as public, and return must be strictly matched.

If the non-Abstract class, all methods in the interface must be implemented; otherwise, it must be declared as an Abstract class, and the subclass of the subsequent subsections must implement the interface, otherwise it must be Abstract.

Implement the interface:

Access-modifier class class-name [extends superclass] [IMPLEMENTS `` Interface [, interface ............]] {

// body of class

} // Access-modifier can only be public or default.

The interface type variable references the object of the class that implements the interface, and the runtime polymorphism is implemented. However, the interface reference variable only knows how the interface declaration. Just like the super class reference variable reference subclass object in Chapter 8. Page 168

Interface extension:

Implemented by inheritance. E.g:

Interface a {

Void meth1 ();

Void meth2 ();

}

Interface b extends a {

Void meth3 ();

}

Class myclass imports b {

Public void meth1 () {

System.out.println ("this is meth1");

}

Public void meth2 () {

System.out.Println ("this is meht2");

}

Public void meth3 () {

System.out.println ("this is meth3");

}

}

Note: When a class implements an interface that inherits another interface, it must implement all the methods in the interface inheritance chain table. Otherwise, this class must be declared as an abstract class.

10 abnormal processing

10.1 abnormal foundation

An exception is a runtime error, including runtime user program errors and runtime system itself error.

Abnormal type:

Throwable is a superclass of all exceptions; two branches:

Exception: Used for user program exception, can be used to create user's own abnormal subclasses. RuntimeException is a more important subclass (including 0 divided and illegal array indexes and null pointers) belonging to non-detection exceptions.

Other detection exceptions.

Error: The system itself is incorrect, for example: stack overflow.

5 Keywords: TRY Catch Throw throws finally.

Abnormal processing: 1. Available exception handler provided by the Java runtime system

2. Users handles exceptions, use try and catch. Role: Correction error is that the program continues to prevent the program from being terminated.

E.g:

Class Excep {

Public static void main (String [] args) {

INT m = 2000;

INT n = 0;

INT K;

Try {

K = m / n; // Throw an exception, the program goes to catch, other statements in the TRY block are no longer executed.

System.out.println ("k =" k); // is not executed

System.out.println ("I am not execute"); // is not executed

}

//system.out.println ("Hear Not Add ANY Statement")

Note: There is no statement between the TRY block and the catch block, otherwise compiles: 'Try' without 'catch' or 'finally'; 'catch' without 'try', try must be used with Catch or Finally.

Catch (Exception EE) {

System.out.println (Ee.toString ()); // Output an exception description string

System.out.Println (EE); // To the same, the toString () method is called by default.

K = 0;

}

System.out.pritnln ("K IS Set" K); //

System.out.println ("this is executed"); //

}

}

10.2 multiple caratch

Each catch clause is sequentially checked, the first matching exception type clause is executed, and other clauses are bypassed. When the matching catch is executed, the code after matching the TRY / CATCH block begins.

Note: When using multiple caratches, the abnormal subclass must be before his parent class. If the subclass is behind the parent class, the subclass will never arrive. The code that cannot arrive in Java will be compiled!

Moreover, there is no other statement between the respective CATCH blocks of the same TRY. Otherwise, the error: prompts 'catch' without 'try', the same, Finally and TRY, there is no statement between Finally and Catch.

10.3 Nested TRY

A TRY sentence can be inside the other TRY block. Each TRY block must have a Catch block or a Finally block corresponding to him, and whether the Catch's exception type is not related to the type of type thrown at the runtime. If you do not match, check whether his outer TRY's catch processing matches, so until one is successful with a Catch statement. If there is no Catch statement match, it is handled by the default exception handler by the runtime system.

After the matching catch is executed, the program is started from this CATCH, and the portion that throws an exception to the match between the matching CATCH will not be executed. E.g:

Class P {

Public static void main (String [] args) {

INT m = 100;

INT n = 0;

INT i [] = {1};

Try {

Try {

System.out.println (i [3]); // Throw an abnormal statement

}

Catch (arithmeticException) {// does not match the exception type thrown

System.out.println ("Error By 0");

}

System.out.println ("try1"); // is not executed

System.out.println (m / n);

}

Catch (ArithmeticException OO) {

System.out.println ("Error By 0");

}

//System.out.println ("t2 ");

ArrayIndexOfboundsexce EE {

System.out.println ("Error By Array");

System.out.println ("try3");

}

} // Program Output: Error by Array

TRY3

10.4 trigger (Throw)

The above is the undetected exception initiated by the Java runtime system. You can use throw to explicitly trigger an undetected or detection exception. The program stops immediately when you touch the throw, look for catchs with its type, all the flows.

Format: Throw throwableInstance // Throw an example of an exception.

For example: This is an example of clearly triggering unspecified abnormalities.

Class P {

Public static void main (String [] args) {

Fun (); // Since this exception can be captured, do not add TRY / CATCH block

}

Static void fun () {// Since the exception can be captured, it is not detected, which belongs to the subclass of RuntimeException, so you don't have to write throws ArithMeticexception.

System.out.Println ("zhengzy");

Throw new ArithmeticException (); // User triggers an AritHMeticeXception exception

//system.out.println ("i am not executed "); // throw can no longer have another (including return), because they definitely not arrive, compile will be wrong! ! !

}

}

operation result:

Zhengzy

Exception in thread "main" java.lang.arithMeticeXception

AT P.Fun (p.java: 9)

AT P.main (p.java: 4)

10.5 throws

Prerequisites: If a method throw is an exception but does not process him, the call for the protection method does not have an exception, it is used.

Class P {// This is an example of clearly triggering an abnormal detection but handling

Public static void main (String [] args) {

Fun ();

}

Static void fun () {

System.out.Println ("zhengzy");

Try {

Throw new illegaCCESSEXCEPTION ();

}

Catch (ILLEGALACCESSEXCEPTIONO) {

System.out.println ("zhenGliping ...");

}

}

} // Method Fun () Abnormally THROW is handled by Catch, so ThROWS is not necessary.

Principle: In addition to these non-detection exceptions such as Error and RuntimeException and their subclasses, other detection exceptions must be declared in the throws clause of the method, and other code must be placed in TRY / CATCH to capture the detection exception when calling the method.

Class P {// This is a way to explicitly trigger an exception but unreated example

Public static void main (String [] args) {

Try {

Fun ();

}

Catch (ILLEGALACCESSEXCEPTIONO) {

System.out.println (oo); oo.printstacktrace ();

}

}

Static void fun () throws illegalaccessException {

System.out.println ("zhengzy"); Throw New IllegalaccessException ("this is message");

}

} The result is: zhengzy

Java.lang.illegaCCssexception: this is message

Among them, it is message can be obtained by oo.getMessage ().

Re-throw an exception:

Class P {

Public static void main (string [] args) throws IllegaCCESSEXCEPTION {

Try {

Fun ();

}

Catch (ILLEGALACCESSEXCEPTIONO) {

Throw io; // Re-throw an exception. The default exception handler processing by the runtime system.

}

}

Static void fun () throws {

System.out.Println ("zhengzy");

Try {

Throw new illegaCCESSEXCEPTION ();

}

Catch (ILLEGALACCESSEXCEPTIONO) {

Throw io; / / Re-throw an abnormality, processed by the Method's caller's TRY / CATCH

}

}

} The result is:

Zhengzy

Exception in thread "main" java.lang.illegalaccessException

AT P.Fun (p.java: 13)

At p.main (p.java: 5)

10.6finally

Finally blocks are combined with TRY, and the FinalLy block will be performed before the end of the TRY. That is to say, it is not possible to block Finally execution, including return, control flow statement, and the like.

Understand user custom exception

Class myException extends exception {// inheritable Exception

Private Int msgnum;

MyException (int a) {

Msgnum = a;

}

Public string toString () {// Tomtring to TOSTRING () method

Return "MyException:" MSGNUM;

}

Class demo {

Public fun () throws myexception {

IF (a> 10)

Throw new myexception (109);

}

In addition, if the code in the TRY block does not have a clear throw detection exception, the detection exception type cannot be detected in the catch block, otherwise, compile the prompt: p.java: 14: Exception java.lang.InterruptedException is never Thrown in Body of Corresponding Try Statement. However, non-detection exceptions in the CATCH block do not matter. All in all, if you throw a test exception, you must detect it in a catch, and the types in the catch must be matched with the throw type or Exception. Otherwise, compile errors, tips: p.java: 12: unreported exception java.lang.InterruptedException; Must Be caught or declared to Be Thrown

11 multi-threaded programming

Threaded status: Running Suspend RESUME BLOCK TERMINATE

Thread priority

Synchronization, Pipeline (Monitor)

Message delivery

Thread class and runnable interface, to create a new thread, you must extend the Thread class or implement the runnable interface. THREAD class management thread:

GetName gets the name of the thread

GetPriority gets thread priority

IsAlive judges whether the thread is still running

Join is waiting for a thread to terminate

Run thread entry point

Sleep hangs thread in a period of time

Start starts thread by calling the running method

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

New Post(0)