Java concept summary

xiaoxiao2021-03-05  19

...

1

◆ Constructor ... 2

◆ Overload and coverage ... 2

◆ Polymorphism ... 2

◆ Class initialization ... 3

◆ Abnormal ... 3

◆ Equals () and ==. 4

◆ String. 4

◆ Packaging class ... 5

◆ MATH ... 5

◆ Collection class ... 5

◆ Identifier ... 6

◆ Switch (i) 6

◆ Garbage collection ... 6

◆ Is A & HAS a. 7

◆ Introduction and anonymous class ... 7

◆ assertion ... 7

◆ Thread ... 8

◆ Other pay attention to problems ... 10

◆ Pass value and pass

Strictly speaking, all method parameters in Java are transmitted. Because even if the parameters passing are the number of objects, the cores themselves are also transmitted. All basic types are piped.

The pass value: The incoming parameters are considered to be internal local variables that do not affect the original value of the external variable.

Biography: For the quoter itself, it is also transmitted, but if the object attribute points to the extremum in the method changes, it will directly affect the object attribute points to the object.

Understanding the best way to pass this concept is to draw a directional view. Eg. Aà (Object) O For A itself, it is a pass value, that is, when A is passed as a parameter, if the other core is assigned to A in the method, when the method returns, a is still It is pointing to the original object without changing. Second, for the pass, if there is a change in the object attribute points to A inside the method, the change in object attribute will be directly real-time.

Also emphasized, all parameter passes in Java is transmitted.

There are many exams for this type of test. There are more basic types of biopsy issues to a certain variable, deliberately trying to change it, then print it when the method returns. According to the validation, it is actually that the variable has not changed.

◆ Constructor

a. The constructor does not return any return type, even if it is Void. If the return value is specified, Java will be considered a general method.

b. If no constructor of the parent class is called, Java always calls the default constructor of the parent class. (The first line will default to super ())

C. Java will not default a default constructor as long as the classes are explicitly defined in the class.

d. The constructor can be overloaded and other constructors can be called in their vivo. But this () and super () can only be called in the first line of the constructor.

e. The modifier of the constructor can only be an access control PUBLIC, PRIVATE, PROTECTED, and (DEFAULT). Other modifications are not available.

f. The constructor cannot be inherited.

◆ Overload and coverage

The overloaded English is Overload, while the overwhelming English is Override. The overload is a plurality of symbol functions in the same category, and override is the same name function in the class inheritance system. (Note: The overlay is sometimes referred to as rewriting)

Overload is determined by the number of parameters, parameters of the same name, parameters, and parameters. The modifier of the method, the return value, and the abnormality thrown cannot be used as the basis for distinguishing the overload method. (There are also overloading phenomena in the inheritance system)

The overlay is a method defined in the subclass of the subclass in the inheritance system. The return type and parameter type of the coverage method in the subclass must exactly match. The access control can only be more publicized; the abnormality thrown is a subset of superclasses or not.

(Static method can not be covered, the private method can not be overwritten. Java treats them hidden)

· The parameter type is consistent, the return type is different, the compilation error, "Try to use incompatible return type overwritten".

· As long as the parameter type is inconsistent, the return type is different from the same, the compilation can be passed, which is not overwriting but overload.

◆ Polymorphism

The polymorphism is in the inheritance level of the class, which is achieved by the mechanism of rewriting upwards and method rewriting. Object-oriented programming is: I hope that the program code written is only working on the base class. As a result, when adding a new inheritance class, most of the program code will be rewritten (i.e., the code has an expansion). So when the newly added inheritance class is called, it will first transform into a base class. This is the polymorphic upward transformation.

This obviously need to rewrite the method in the inheritance class by calling the basic class by calling the base class. And which inheritance class is called, which is determined by the dynamic binding of Java.

The most important point of polymorphism is Run-time binding. Polymorphism is the target for object-oriented programming.

About the coverage of the polymorphism is as follows:

Attributes can be inherited and can be "overwritten". However, this feature is not dynamically bound to attributes, so the overlay attribute is considered to be a special attribute of subclasses. In a sense, attribute determines class (nature). On the other hand, the type of declaration determines the properties of the object. This is because any object or variable equal sign is used to assign a value to the left, so the type of the left is prerequisites, and the value must be in accordance with the type of declaration. For the upward transformation, the object IS A, the object IS A, the right, is established. Be sure to remember that attributes will always follow the declaration type. However, the method is dynamically binding at runtime, it depends on the actual type of the object itself (in fact the method, it is also checking the base class after the upward transition, if there is no definition of this method, Then compile the error, then dynamically bind to the overlay method of the inheritance class).

In addition, the Static method cannot be covered, and the Private method cannot be covered.

It is also necessary to pay special attention to the method, if it is covered, if it is covered (for example, the parameter is consistent, only the return type is different), the compile will be error, not by Java, it is considered to be overloaded (unless the parameter type is different, so Java will think Not Override, in fact it is Overload).

◆ Class initialization

The initialization of classes is roughly such as many aspects.

a. Initialization B of static variables B. Initialization C in general instance variables. Initialization of constructor

The difficulty of initialization is in the inheritance system. When there is a inheritance system, the principle that initialization always follows is that the basin is initialized.

0. When it is loaded into the current class, if the current class has inheritance system, the base class is loaded in turn.

0 '. First initialize its static STATIC variables from the top base class, then initialize the static STATIC variable of the current class (that is, the initialization of the Static variable is initialized with the class being loaded, and its initialization is performed in any constructor. before)

1. First, the base class object is constructed from the top-end base class.

(If there is a THIS or Super call in the constructor, then do this first)

1.1. First, according to the initialization of the initialization

1.2. Execute their constructor

2. Recursive steps in sequence

◆ Exception

Throws is an abnormal state of declaration, which is placed in the definition of the method; throw is a throw of abnormality, which is placed in the method.

Exceptions can be divided into detectable exceptions and non-detection abnormalities, and the call has been carried out to be able to detect an abnormal method.

a. The method has stated that the detectable abnormality, the block that calls the method must capture an exception, otherwise it is wrong B. Throw can't follow any statement, otherwise compile the statement to not arrive

C. Multiple CATCH statements require more specific exceptions before, the super-class is abnormal, otherwise compiling an error

d. The Finally statement will execute before the RETURN statement, that is, the finally statement will be executed before the method is jumped out.

e. If you encounter system.exit (0), no matter what, the program immediately exits, the finally statement does not execute

f. The method has declated an abnormality, but it can throw an abnormality in the method.

g. No Catch capture can not be captured when the method of detecting an abnormal is detecting, otherwise compiling an error

Other pay attention:

The method covered in the A subclass can only throw an abnormal subset of the parent method, or no exception is thrown (this is a subset)

b However, for non-detection exceptions RuntimeException will not be subject to the above constraints, they can be thrown at any time. Not scope restrictions.

C When the inherited subclass does not have an abnormal abnormality, if its examples are declared as superclass (upward), then the subclass does not have an abnormal approach, and the Catch, the program is also compiled. (Methods in actual operation call or subclass)

◆ Equals () and ==

For the above about equals () summarize as follows:

a. Two objects that are incompatible with type can be used in equals (), but as long as the object type is different (even the same value), return false

b. For classes that are not overwriting Equals (), even if the object type is the same, the value is the same, but the return is still false because it is used by the default Equals method of Object (==)

C However, for the class of Equals (), just returns TRUE as long as the value is the same. These classes are String, Wrappers, Date, Calendar, BitSet, etc.

For == summarization as follows:

a. Two objects that are not compatible can not be used ==, if used, compile errors

b. The same type of object, if it is not to guide the same object, return to false (only to TRUE with the object pointing to the same memory block)

C. Some of the String case, because the String object has a literal and constructor. The literal object is placed in the buffer pool, which means that if the two graphics values ​​are the same, the second object will point to the first object that already exists without new generation, so == returned True. The object generated by the constructor is the same general object. For a word, multiple classes share the same buffer pool. This means that it is still the same object in another class in another class.

In addition, pay attention, TOUPPERCASE (), how to () method, if the case is not different from the original String, the method returns the original object, == Returns true.

d. For basic types, the system will automatically return to a precision, then the value is compared, and the value is returned to TRUE.

◆ String

The most important point of the String class is "immutable". It means that once the String class is generated, it will not change again. If you try to change it, it will generate a new object. String objects have a literal and constructor. The literal object is placed in the buffer pool, which means that if the two graphics values ​​are the same, the second object will point to the first object that already exists without new generation, so == returned True. The object generated by the constructor is the same general object. For a word, multiple classes share the same buffer pool. This means that even if you create a literal string in a prior class in another class, it is still the same object.

It should be noted in the exam: s = new string ("abc"); s = "def"; system.out.println (s);

s = new string ("abc"); S.Concat ("DEF"); system.out.prinln (s);

The previous program is printed as "abcdef", and the last program is printed as "ABC". The difference is that the first program is re-assigned to s. In the second program, S.Concat ("DEF") just produced a new object but did not assign it, but the original S did not change.

In addition, it is variable to StringBuffer, any change to it is real-time.

◆ Packaging

The packaging class is to facilitate the manipulation of basic data types. With a lot of packaging, you can use a lot of ways to manipulate the basic data type (without packaging classes, it is inconvenient to the basic data type operation, unless you write methods).

To familiarize with the packaging class, you should understand the following:

a. Packaging class constructor. Generally speaking, the packaging class constructor parameters have two types: basic data value, string

Note: When the Boolean package constructor is incorporated into the string, other strings return to False except for the case where you are in a string.

b. Common way of operation. For example: transition to this basic type or other basic type

Eg. Bytevalue (), INTVALUE () ...; ParseByte (String s), Parseint (String s) ...

C. Valueof uses for use. Valueof (STR) is a static method of packaging classes and is equivalent to constructors. It analyzes the incoming parameters and constructs a package class of the same type and returns the package class.

Example: Original type à string (New Integer (101)). Tostring (); String.Valueof ("101")

String à (Packaging Class) à Original Type Integer.Parseint ("String");

(New Integer ("101")). DoubleValue (); Integer.Valueof ("101"). INTVALUE ()

◆ MATH class

There is a static method in the MATH class. One of the most error-prone is three methods: CEIL (), floor (), runk ()

It is also important to note that there are many ways to have multiple overload versions with different basic data types. Eg.abs (), max ()

a. CEIL () method. This method returns the type Double Double, takes the nearest integer in a single positive coordinate direction.

b. Floor () method. This method returns the type Double Double, takes the most close to its negative integer.

C. Round () method. It has two overload versions: Double and Float, return to long and int

Long Round (Double A); int Round (Float)

Round () method = Math.Floor (A 0.5), which means positive 5 into, negative number 6 into Eg.system.Out.println (Math.ceil (Double.min_Value) //1.0

System.out.println (Math.Floor (-0.1)) //-1.0

System.out.println (Math.Round (-9.5)) // - 9

System.out.println (Math.Round (-9.6)) // - 10

System.out.println (Math.Round (double.min_value) // 0

◆ Collection class

The Collection class provides the convenience of the holding object and the convenience of the holding object. As it is named, collecting the various types of objects together, and the number is not limited (a bit like collecting bags). Collect will be regarded as Object (up), so when the element object is removed, it must be explicitly explicitly (ie, forced transformation) indicates its type.

Object collection is divided into Collection interfaces and MAP interfaces as a whole. This classification of the classification is: the number of placed elements objects at an element location. Obviously, the MAP interface is placed a pair.

The Collection interface can be extended to two basic interfaces: LIST interface and SET interface.

According to the above, the object collection can be divided into four basic types: Collection, List, SET, MAP

· Collection It is an interface of a base class, without any restrictions on the element, can be repeated and disorder.

· List is an orderly list known from its name. It describes that the object is placed in it in order. Obviously, the elements of the post-placed may be the same as those previously placed. So, List is an ordered list of options that allow for object repeated.

· SET is actually a collection of mathematics, which does not have repeated elements. Among them, there is a space set (ie Null object). The elements in the SET are not required.

· Map is mapped to describe the search for objects with Key and Value. The uniqueness required in the Key domain (actually a set), the Value domain can allow repeated elements (actually a collection). Also note: Common HashMap is disorderless, while TreeMap is in order.

◆ Identifier

a. The first character of all identifiers must be letters (case), underscore _, dollar sign $ (or symbol ¥)

b. The next item can be the same type of characters (letters, _, $) as the number (0-9) and the first character, and any other special characters cannot be

C. The identifier cannot use Java keywords and reserved words (50). But note that like Java, Integer, Sizeof, Friendly, etc. is not a Java keyword.

d. Identifier case is sensitive, but there is no limit to the length.

◆ Switch (i)

a. The highest precision in the Switch (i) is int (or short, byte, char), but not long, float, double

b. The default statement can be placed anywhere (Default means that all values ​​in Case)

C. When you don't add a BREAK statement in the statement, the program starts from the match (including matching the DEFAULT statement), and all statements will be executed (regardless of matching whether it) is encountered until the BREAK statement or Switch tail is encountered. ◆ Garbage collection

a. As long as an object loses all Reference, you can consider collecting garbage collection stacks.

B. When all of the reference to an object is lost, JVM just considers garbage collection, but does not mean that the memory of this object is immediately retracted, even at all. JVM will only carry out garbage collection only when more memory is needed to continue the program.

C. In most cases, you will never know when garbage collection will happen. Java will run the garbage collection process as a low priority thread. Waste collection in Java cannot be performed immediately. Call system.gc () or runtime.gc () static method cannot guarantee the immediate execution of the garbage collector, because there may be a higher priority thread.

D. If you want to manually call garbage collection, and want to execute some tasks you want when collecting objects, you can override a method called Finalize (). Java will only call all Finalize () methods for each object. The Finalize () method must be declared as protected, not returning any value (VIOD), and it is necessary to throw a throwable object and must call the super-class Finalize () method ("Super.Finalize ()).

Eg.protacected void finalize () throws throwable () {

Super.Finalize ();

............;}

◆ Is A & Has A

Is A describes a superclass and a subclass of relationships, that is, inheritance relationship.

Has A described is a part of an object is another object, that is, a combination of relationship (or call).

◆ Introduction and anonymous class

Introduction is included in the class included, there are three aspects that need to be aware: general intracence classes, within the method, in -ty, static inside.

· Generally, it can be treated as a "instance variable" as an outside class. Therefore, four access controls public, protected, default, private. Just pay attention: To generate this inner class object outside of the Non-Static function outside the outside, you must specify the type of the inner class object in the form of OuterClassName.innerClassName. Generally, an internal category must be related to an object to which it is outside.

Generally, inside categories cannot own Static members.

· The method is within the range of the range, that is, you can't call the inside category outside the method, from which it can be considered a local variable. However, although it has its category, after all, the inner category is still class, it will not disappear as the return of the method, it is still considered as class by Java.

A. Methods Any member of the inside category can directly access the outside class

B. Methods Intrinsically, only access to Final type local variables and Final type method parameters in this method.

C. Methods Intrinsically, any access control is repaired (this is the same as local variable)

· Static Introduction It does not need to have an external object when it is generated. It can be considered a static function.

The STATIC internal category can be placed in an interface.

· Anonymous class is actually an unknown class that inherits from the New class. The Reference returned by NEW will be automatically transformed. Anonymous classes cannot have a constructor, but can be stated by default or parameters of the base class.

Anonymous classes add any modifiers (follow the superclass modifiers), and do not implement the interface, throw an exception.

◆ assertion

As a new-added function in Java 1.4, it is a new error check mechanism in Java, which provides a mechanism for correcting the correctness check in the code, but this feature can be turned off as needed. Assert keywords, AssertionError classes, as well as several new ASSERT methods in Java.lang.classLoader. The most important feature of Assert is that an ASSERT statement can be turned on or off at runtime, which is closed by default.

The assertion statement has two legal forms: a. Assert Expression1; B. Assert Expression1: Expression2;

Expression1 is a Boolean expression that must be guaranteed to be true during program execution; Expression2 is optional, and it is optional, which is used to pass to the constructor of an exception AssertionError, so therefore The type of Expression2 must be the parameter type of legitimate AssertionError constructor. In addition to a default constructor without parameters, AssertionerRor has seven constructors with a single parameter, respectively: Object (eg.string) Boolean Char Int Long Float Double. In the first form, if an exception is thrown, the default constructor of AssertionError is called. For the second form, the seven single parameter constructor is called according to the type of Expression2 value.

A. Compilation of an Assert program: Javac -Source 1.4 Testassert.java (prompt java compiles 1.4 version)

B. ASSERT program Operation: Java -ea Testassert or Java -ea: Testassert Testassert

Other operating parameters: java -ea: pkg0 ... testassert; java -esa; java-dsa (system class assertion), in addition, can also be used simultaneously. When a command line uses multiple-EA-DA parameters, follow two basic principles: The following parameter settings overwritten the settings of the front parameters, and the specific parameter setting will overwrite the general parameter settings.

C. The AssertineError class is the direct subclass of Error, so the representative program has a serious error, which is usually not required to capture the programmer using the Catch statement.

D. Criteria for using Assert: The role of an ASSERT statement is to ensure consistency within the program, not the consistency between the user and the program, so it does not apply the correctness of the command line parameters. Can be used to ensure the correctness of the pass to the private method parameter. Because private methods are only called inside the class, the programmer can control, we can expect its status to be correct and consistent. The public method is not applicable. In addition, the Assert statement can be used to check the correctness of the status at the end of any method, and the initial state of the start check related to the method.

The ASSERT statement does not constitute a part of the normal operation logic, which is always remembered that they may not be executed.

◆ thread

The thread is to run the program to run a large number of CPUs and easy to fall into the dead cycle. As a thread to run (i.e., the thread is a code block).

Threading is started, it will enter the READY state (actually the Runnable status, just waiting to allocate the CPU). This also shows that the thread will not immediately run uncertainty. After the thread is started, as long as the Run () method is not jumped out, there is always an opportunity Running, which is automatically assigned a CPU time in each thread to Running. It is necessary to keep in mind that thread runs and interrupts have uncertainty, you will never know when threads will run, when will be interrupted. From the perspective of the object, it can also be an object. It can be considered as one of the other objects.

Pay special attention to several concepts in the concept of thread: single thread, multi-thread, multithreaded operation, multi-threaded synchronization (resource access), multi-threaded communication.

· Single thread is relatively simple for single-threading, it is relatively easy to understand because it does not involve Synchronized and Communication issues. There are two ways to create a single-thread, which extends the Thread class, which is class a extends, {public void run () {}; ......}; Second, implement Runnable interface, Class B Implements Runnable {thread T = New Thread (this); public void run () {}; ......

· Multi-thread relative to single threads, many multi-threads will complicate, the reason is that they will involve resource access and multi-threaded communication issues in multi-threaded rooms. This involves the three aspects mentioned below: multithreaded operation, multi-threaded synchronization (resource access), multi-threaded communication

· Multi-threaded operation For multiple threads that can run runnable, running and interrupts have uncertainty, never know when threads will run, and when it is interrupted. However, multithreading operations also follow several principles: If multiple threads have the same priority, the system will switch between the CPU time between them; JVM is based on priority to determine the operation of the thread, but this does not mean a low Priority threads have never run.

• Multi-thread synchronization is connected by thread access to each object that is only one thread access control, and the lock controls the access to the sync code of the object. This object that can be accessed by multiple threads is the resource sharing problem.

A. In the program, the calling thread can be used to obtain the control lock of the object by defining a synchronized code block or multiple Synchronized methods. By obtaining the lock of the object, the thread prevents other threads from operating the synchronization block or synchronization method defined by the object (specifically, this time does not guarantee the non-synchronous variables and non-synchronization methods of other threads on the object. Operation operation).

B. The thread is only released after the synchronization block or synchronization method returns.

C. Synchronized does not guarantee the running continuity of the program, but only guarantees the identity. That is to say, even in the Synchronized block or method, the running of threads still has the possibility of interrupt. Despite this, it ensures that other threads will not access other synchronization blocks and methods of the object because the object lock is not released. This fact illustrates that "multithreaded run" and "synchronization between multi-thread" are two independent concepts.

D. Multi-threaded synchronization blocks or methods can be placed in any object that can be accessed (including thread itself, which can actually be accessed by other threads).

• Multi-threaded communication multi-threaded synchronization Eliminates a thread that occurs when changing another thread's stable object state, but in terms of communication between the thread, synchronization is not a role, that is, "multi-threaded Communication between "is another independent concept. Multi-threaded communication is usually implemented by Wait (), Notify (), and the summary of these two methods is as follows: 1.Wait (), notify () belongs to the Object method, not a thread method

2. Object.wait () means: call me (refer to the object), you have to wait, that is, let ... (call my current thread) ... Waiting

Object.notify () means: This awakening other calls over me and waiting for threads

As described above, Wait (), notify () object is a shared object to be used (of course, shared objects can be threaded), but its method action is for calling it. (Usually, the object's method is acting on its own attribute, and rarely acts on other objects. To use other objects, use call Object.Method ())

3. Wait (), notify () must be paired, and there can be three forms.

A. {wait (); .... notify ();

B. {Wait ();} ... {Object.notify ();

C. {NOTIFY ();} ... {Object.wait ();

4.Wait (), notify () must appear in the Synchronized method or block, otherwise an exception will occur. The reason is because WAIT () will release the object lock, and the lock must be in the synchronization method or block. In addition, Wait () is the same as SLEEP (), must also capture an abnormal interruptedException.

5.Wait (), Notify () Execution is generally related to the external conditions, only the condition changes that the wake-up waits is triggered. This change is usually in the form of a flag (TAG), i.e., after a certain method is performed, the flag value should be changed immediately. If the thread is required to alternately, it is also necessary to join the judgment of the mutual exclusive condition. {if (a)} in synchronization method 1, {if (! a)} in synchronization method 2

6. When notify () is performed, the program does not immediately run call Wait () threads, and until the Notify () object lock is released. After the release is complete, the program reassigns the CPU. It should be noted that the system does not necessarily let Wait threads run, and it is possible to continue to operate with the notify () thread. This is an uncertainty of thread operation and interrupt.

7. Generally speaking, notify () is a thread that wakes up waiting for the longer waiting for the pool; NOTIFYAll () is all waiting threads in the wait in the pool, and threads to compete object locks. It is said that the general situation is sometimes the case, this is determined by the uncertainty of thread operation and interruption in the system.

8.Wait (), NOTIFY () Normally requires a mating of Sleep (), otherwise the running explicit in the screen will "speed".

9. Multi-threaded communication will have a deadlock, that is, WAIT threads may never have object locks.

-------------------------------------------------- -----------------------------

◆ Other payment questions

☆ array

a. Before using the array, you must guarantee the assignment of memory (the system will initialize the default value), which cannot be defined. Otherwise, an empty pointer error will occur by running. The allocation of the memory is only available to pass NEW. b. The second dimension of the two-dimensional array can be growing, and the specific value can be not specified when defined. This means that the two-dimensional array in Java does not have to require both the length of each dimension as the matrix.

☆ Variable assignment

a. Example variables can only be explicitly assigned at definition, and they cannot be defined first, and then assign (such a compilation error).

b. Method variables can be explicitly assigned during definition, but also definition before defining.

C. Static variables can be assigned anywhere in the class (if the value is assigned in the method, it is actually a value).

d. Final variables can be assigned anywhere, but once they assign values, they are not allowed to be re-assigned.

e. The Static Final variable can only assign a value (ie: constant) at the definition.

☆ shift

a. >> The first copy right shift. The division is equivalent to the symbol.

b. >>> Zero fill right shift.

C. << Left shift. It is equivalent to a symbolial multiplication, but must follow the principle of an integer.

d. >> 32 >>> 32 Any number of digits is all the remainder of the shifting 32. Eg. Move 32 points.

☆ Byte, Char and Int

Since the value range of Char is the same range, the total value of the INT is the same, the whole texture can be directly assigned to the char. However, if you express a whole (int) variable directly to the char variable, compiling errors.

In addition, INT i = 5; CHAR C = 'a'; C = i; compilation is passed.

The BYTE type is overflow when the range is exceeded when the transformation is forced.

☆ SD%

Survive only the symbol on the left, right on the right.

Eg. INT A = -5; int b = -2; system.out.println (a% b) // - 1

INT A = -5; int b = 2; system.out.println (a% b) // - 1

INT A = 5; int b = -2; system.out.println (a% b) // 1

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

New Post(0)