Think in Java notes

Source: Internet
Author: User

Today, when I was sorting out the materials, I suddenly found the notes I made when I was reading think in Java (Java programming ideas). I thought it was good and I would like to share it with me, it is also the best memory of my consistent publication.

I suggest you read this book, whether it is basic content or .. All of them are very careful.

 

 

In an early Java speech, Bill Joy (one of the founders) claimed that "Java = C ++ --"

 

Principle: Program Design separates changing things from unchanged things.

// The above is a famous saying

 

1. Hide the implementation scheme:

 

(1) set all attributes to private to avoid direct access to the attributes, but only provide corresponding methods to access the attributes. (2) Abstraction: The Implementation class is separated from the interface, and only the corresponding interface is provided for the outside world. The specific implementation of the hidden method has the following functions:. avoid programmers who should not be exposed to implementation details to change the implementation details and affect the use of other users. B. Allow the Database Designer to modify the internal implementation details without affecting the client programmer. Because only interfaces are injected into their programs.

 

 

 

2. reuse of the solution:

 

Repeated use of code and design schemes is the most important part of object-oriented design.

 

Include (organization) Relationships: for example, a single transmission is set as a class, a car is set as a new class, And a transmission object is injected into the new class of the car, this kind of change requires that the vehicle type of the transmission can be used. This is a good way to implement code reuse, there are several kinds of cars that need to be repeated several times, so this design will look very bad.

 

Inheritance relationship: an important internal processing is to treat the struct class as a base class, that is, there is a parameter as a base class method. At this time, we can call the method and pass the parameter as a struct class, the program will correctly process it into a derivative type, which is called upcasting ).

 

The program automatically calls the method of the corresponding class based on the type of the passed parameter (The subclass may overwrite the method of the parent class ,), the compiler and running system are responsible for all the implementation details without our own control. This situation is called "multipleth", and the implementation of multipleth is called dynamic binding.

 

When selecting a class relationship, we should first consider the Organization (Inclusion) relationship, and then the inheritance relationship. inheritance will make the program very complex.

 

 

 

3. Use of the Set:

 

The best way is to automatically change the accumulated implementation mode based on the method used by the set, so that we do not need to select, delete, update according to different requirements ), but on the other hand, the efficiency overhead of the set is relative to the overhead of the spam processor and the overhead of running in the window, not much.

 

When performing an iteration on the collection elements, it is best to select an iterator to use it with all the collection classes.

 

 

 

4. Java implements the design mode of a single structure, that is, all classes are ultimately inherited from a base class (object class ). In this way, all objects of all classes have a common interface, so that they all belong to the same type. Convenience: A. This allows all objects to have some basic operations, and all objects are created in the memory heap, which greatly simplifies parameter transmission.

 

B. More convenient Implementation of the garbage collector, some necessary support can be installed in the basic class (that is, object), the collector can send appropriate messages to all objects.

 

 

 

5. Java programming is simpler than C ++:

 

A. java uses a single structure, and we can only create objects (new) in the memory heap in one way, instead of creating objects in the stack, while C ++ allows creation in the stack, in addition, it is the most effective way to allocate and release buckets, and creating objects in the memory heap is costly during the runtime. B. Java uses a garbage processor for garbage collection, and then automatically releases the memory occupied by those objects. In C ++, after an object is used up, it must be displayed and deleted. (The garbage collector of the Java System has always been an unclear structure. Sometimes we need to avoid the Garbage Collector (Real-Time System) in special programs )).

 

 

 

6. multithreading:

 

Multi-thread processing is usually quite simple, but when multiple threads run at the same time and attempt to access the same resource, some processing is required: A shared resource must be locked when used, that is, each thread accesses the resource in sequence. The resource is locked when accessed, and the resource is unlocked after being accessed,

 

At the same time, only one thread can use a specific memory space (a type of resource). To achieve this, you must use the synchronized keyword. Other types of resources must be explicitly locked by the programmer, A programmer is usually required to create an object that represents a lock. The lock must be checked every time multiple threads access the resource. In the design of the singleton mode also used: http://www.cnblogs.com/shenliang123/archive/2012/03/26/2417968.html

 

 

 

7. Web: Client/Server:

 

(Server: Aggregates various elements and information warehouses, software used to deliver information, and machines used to store the software .)

 

 

 

8. Java is not a language that can be easily learned. Classes in Java are only complex types.

 

 

 

9. java applets can be embedded in HTML. when accessing a server, the server will send the HTML and Applet together to the client's browser according to the request. This application is quite good.

 

 

 

10. server-side programming: the browser sends a complex request to the server, which usually involves database transactions. After processing, the server will format it as HTML and return the result, all these requests must be processed by the server code, and all the server code is very important (servlet ).

 

 

 

11. comparison between Java and C ++: each has its own advantages. It acts on different fields, and the powerful type check and Error Control Systems of Java are incomparable, java running speed is not comparable to that of C ++, even though it has been greatly changed.

 

 

 

12. You can select JDBC, hibernate, JDO, JDO, and hibernate for database connection.

 

But JDO is for database tables, while Hibernate is for class objects.

 

 

 

 

 

Chapter 2: Everything is an object

 

1. Use a handle to operate the object:

 

In Java programs, everything can be seen as an object, but the operation identifier is actually a "handle" pointing to the object, just like a TV and a remote control (the TV is an object, the remote control is a handle, in fact, all operations are performed on the remote control), but not every handle must correspond to an object, but it is best to initialize each variable declaration.

 

 

 

2. There are 6 data storage locations in Java:

 

A. Register (inside the processor): the memory volume is small and is allocated by the compiler. We do not have direct control.

 

B. stack (located in the random storage access zone [Ram]): Generally, object handles are stored here, stored by moving pointers, and memory is released, however, objects are not stored here. during storage, the compiler must accurately know the length and storage time of all stored data, affecting flexibility.

 

C. heap (memory heap RAM): used to save objects. As long as there is new code to create objects, it can be automatically saved during running, this makes it more flexible for the compiler to know how many objects to store and how long the objects are stored. However, it pays for the memory allocation during runtime (with exceptions, to ensure efficient access to small and simple objects, Java does not use new to create a variable that is not a handle to store actual values and store them in the heap ).

 

D. static storage: it is located at the specified location of Ram. It is indicated by the static keyword that some elements of an object are static, but an object will never be in the static storage zone.

 

E. Constant storage: store constants directly inside the program code,

 

F. Non-ram storage Zone

 

 

 

3. Two classes are added to Java for progress calculation: biginteger and bigdecial.

 

Scope: it is determined by the angle brackets. If the variable X has been declared in a large scope in Java, it cannot be re-declared in a smaller scope.

 

 

 

4. Java assigns an initial value to the global variable (the default value of Boolean is false), but local variables are not initialized. An error is reported during compilation. Therefore, local variables must be initialized.

 

 

 

5. java calls a method in a class, first instantiates an object (except static), and then uses an object to call the correct method. object-oriented programming is usually called "sending information to an object ", for example

 

Int x = A. F (); Other A is the object, and F () is the message.

 

 

 

6. static Method static: the static method is mainly used to call its method through a class. In a static method, only static member variables can be used, because non-static member variables must be instantiated through objects, you can solve other problems by grasping static methods and not creating classes.

 

 

 

7. document notes:

 

Class document Tag:

 

@ See: Class Name/complete class name # method name, indicating to reference classes in other documents

 

@ Version: version information, @ Author: Author information, HTML embedding

 

Variable document Tag:

 

Only embedded HTML and @ see references can be included.

 

Method document Tag: In addition to embedded HTML and @ see references

 

@ Param Parameter Name Description @ return value description @ exception complete Class Name Description

 

 

 

8. The assignment from one object to another is to copy the handle from one place to another. c = D means that the C and D handles are all objects corresponding to D.

 

Another phenomenon is "alias": copying an object A to another object B will be automatically cleared by the garbage collector. In this case, B is equivalent to the alias of object, all objects point to a. In this case, A and B can be used to change the attribute values of objects. The alias is described in detail below.

 

 

 

9. logical operators: & | is a feature of "short-circuit" operations, that is, the values returned by an explicit expression are not calculated downward, & | does not have this feature. All expressions are computed and returned.

 

 

 

10. The only place for Java to use commas is the for loop.

 

 

 

11. c ++ contains the sizeof () method to obtain the number of digits that data types occupy on different computers. Java does not include this method, because all data types in Java are of the same size on all machines.

 

 

 

12. labels: for Java, the only place where labels are used is before nested loop statements. The position is near the beginning of the loop statement. It is best not to insert anything else between the two, the reason for embedding tags before loop statements is that break or continue can jump out of multiple loops, Because theoretically both break and continue only interrupt the current loop.

 

 

 

13. after the float or double type data is converted to an integer, the fractional part is always "cut" without any carry processing. the range of random numbers generated by rondom () is [0, 1 ).

 

14. Method overload (heavy load ):

 

It is the same method name, but the type, quantity, and order of the method parameters are different. The return values of methods alone are not called method overload, because sometimes we do not care about the return values of methods, for example, if F () is called, the compiler cannot determine whether the called method contains the returned value or does not contain the returned value.

 

 

 

15. If there are two objects of the same type, what if the same method is called for the two objects? For example:

 

Class ban {

 

F (){

 

.........};

 

}

 

Ban ban1 = new ban (); ban ban2 = new ban (); ban1.f (1); ban2.f (2 );

 

So there is only one f () method, so how do you know whether ban1 is called or ban2 is called?

 

In fact, the compiler will do some behind-the-scenes operations for us. It will pass the handle as an independent variable to the method F (). Therefore, after compilation, the first two methods become F (ban1, 1); F (ban2, 2 );

 

 

 

16. This Keyword:

 

This indicates this object or the current object, and generates a handle for the current object.

 

  1. Call the builder in the builder: you may need to call an exception constructor in a constructor. To prevent code duplication, use this, but you can only call it once, it cannot be called twice and must be placed at the beginning.

 

 

 

17. Define an object handle within a class. If it is not initialized as a new object, the handle will get a null value.

 

 

Chapter 2: hiding the implementation process

 

"A basic consideration for object-oriented design is how to separate changing things from what remains unchanged"

 

  1. Java interpreter's working program (the browser generally contains a Java interpreter): first, it will find the environment variable classpath (which must be configured when JDK is installed ), classpath contains one or more directories as the root. class file search.
  2. When the interpreter encounters import, it searches for the specified path under classpath, finds the subdirectory (provided package name), and then finds the compiled file with the appropriate name.
  3. Sometimes we want to create some new tool classes by ourselves, so we can compile these classes into the tools directory, such as system. out. if println () creates an alias, you can write a class by yourself:

 

 

 

 

 

 

 

 

 

 

  1. Java's default access has no keywords, but it usually becomes "friendly" access, which means that all other classes in the package can access this friendly class member now, however, the classes outside the package are private. Therefore, the "friendly" element has the "package access" permission. However, if there is a public static method in the class, the static method can still be accessed outside the package through the class name, although the object of the class cannot be created.
  2. During subclass instantiation, before the subclass object is instantiated, the program will first call the constructor in the parent class and then call its own constructor, however, the base class constructor called is the default constructor. To call the parent class constructor containing parameters, you must display the call (with the super keyword ). In fact, a super () Statement is implied in the subclass structure. Therefore, if the constructor of a class is privatized, the class cannot be inherited. The quilt override method cannot have more strict access permissions than the parent method. You can use super to call methods in the parent class. The total private method of the parent class cannot be overwritten.
  3. When creating a class, we can design it like this: Write the Public Member at the beginning, followed by the protected and private members. The advantage of doing so is to be able to read from top to bottom, first, we can see the most useful (public) for ourselves ).
  4. Each non-basic data type contains a tostring () method. Sometimes we need to rewrite this method for output convenience.
  5. Create an object handle: You can initialize an object in the following circumstances. A. When the object is defined, this means that they are certainly initialized before the constructor is created. B. In the constructor of that class. C. When the class is actually required.
  6. Merging is to add another class handle to a class and then initialize a corresponding object. How to choose between merging and inheritance:. if you want to use the features of an existing class in the new class, instead of using its interfaces, you can use synthesis to embed the object class of an existing class to implement the features of the new class, so that users of the new class can see the interface we have defined, rather than the interface of the embedded class. This requirement requires that the private object of the existing class be embedded in the new class. Car is a good example of synthesis of engine, door, window, and wheel. Inheritance and synthesis are very important when designing a class. We need to consider the details. We can re-conceive the project at the completion of the Project to see if the structure is reasonable. The focus of the selection is whether to use existing class interfaces. inheritance is required. If you only need an existing class feature to implement the new class interfaces, synthesis is used.

 

Summary inheritance relationship = "the new class belongs to a type of the existing class"

 

10. (): converts the sub-class handle to the parent class handle. You can call the method that uses the parameter as the parent class, but the passed parameter is the sub-class handle. This is convenient and saves a lot of code. Otherwise, you can write a method that can be called by both the base class and the callback class in a class, then, you need to repeat the number of category classes to write this method several times. If you use the upstream styling, you can write only one parameter for the base class, And the subclass can also be called as a parameter, in addition, if we add more category classes in the future, it is not used to change this method, and the software has better "scalability ". During compilation, the method cannot determine which callback class of the base class the input parameter belongs to. Therefore, in order to complete the call smoothly, you need to "bind later ", more accurately, it is called "dynamic (runtime) binding" to determine the type of the corresponding object at runtime, and accurately execute the corresponding method (in this way, a special tag must be installed in the object ). However, if a method is declared as final, the compiler will not execute "dynamic binding", so the execution speed will increase. In this way, we can use a new instantiation method: base class handle = new struct class (); in fact, we create a struct class object, but the handle points to the base class, pass this parameter to the corresponding method and call the method of the object corresponding to the handle. At this time, the compiler will know that it will call the override method of the handler class (dynamic binding has taken effect ). Another point is that if the method name of a method in the override class is the same as that of the base class, but the type or sequence or number of parameters are different, this is also called overload (rewriting ).

 

11. use of final:. in the basic data type, the final modifier is used to indicate that the data is a constant and cannot be changed. The initial value must be assigned (or an expression ), for example, if a handle (an object or array) is modified, the handle cannot be directed to another new object, but the attributes or values of the object can be changed. When both static and final are modified, the data is a global constant (generally in uppercase ). No matter whether it is static or final, the value is unknown during compilation. It is only known during runtime (initialization. B. The independent variable is modified with final. If the method parameter is set as final, the object corresponding to the parameter handle cannot be changed within the method and can only be read. C. The method is modified by final. Reason 1: you do not want the inherited class to overwrite or rewrite the method to prevent the inherited class from changing its original meaning. Cause 2: the code execution efficiency increases. (But be careful when doing so ).

 

12. class initialization sequence (including inheritance): The loader first finds the class from the outside and then checks whether there is a base class (extends). If yes, it loads it, whether or not the base class object needs to be generated, this process will occur. If the base class also contains the base class, it will also be loaded, and so on. Static initialization will be executed in the base class, initialized in the category class, and so on. It is important to ensure this order, because the initialization of the category class may depend on the base class members. At this point, all necessary classes have been loaded and you can create objects. First, the basic type data in this class is initialized to the default value, the initial value of the object handle is null (the bucket allocated to the object is initialized to binary 0), and then the base class constructor is called. This call is automatic. We can also display the call (Super) by ourselves ), if the constructor of the base class contains the abstract method of the base class, the implementation of the subclass method will be called. The construction of the base class adopts the same processing process as that of the class constructor. After the basic class builder is complete, the instance variables are initialized in the original order. Finally, execute the remaining part of the builder.

 

13. abstract class: The methods can only be declared. There is no method subject or a complete method. In this case, the class must be declared as abstract, and the abstract method of the base class must be implemented in the Entity class, there are also exceptions. If this is not implemented, the category class must also be an abstract class. Abstract classes cannot be instantiated, ensuring their "purity ". Interface: it is a deeper abstraction of abstract classes. Interfaces also contain data members of basic data types, but they are static and final by default. in general, we will first select an interface because it also benefits the abstract class and interface. Extends can inherit an interface to extend the content of the new interface, and supports multiple inheritance at this time.

 

14. because all fields in an interface automatically have the static and final attributes, a good tool for grouping constant values in all interfaces is used externally. the constant is referenced, but only the number of basic data types is obtained without additional type security. For example, the int variable used to represent a month, an integer may be obtained. The following processing is reasonable:

 

 

 

 

 

 

 

This is a final class. Other classes cannot inherit from it, and the constructor is private, so they cannot be instantiated. the only instance is the final static object, they are created in the class itself, so that they can be called by name or array index. In main, we can know that the type is safe because M is an object, you can only assign mon22.

 

15. internal class: place a class definition in another class. The internal class requirements are not too obvious, at least they do not immediately feel that they want to use the internal class, the external class has a method, and the return value of this method is the handle of the internal class. to generate an object of the internal class outside of the external class non-static method, the object type must be set to "external class. internal class ". Use internal classes: (1) we are going to implement some form of interfaces so that we can create or return a handle. For example, when we are going to roll back to a basic class (especially an interface ), the internal class begins to play its key role (from the implemented object to an interface handle, it has the same effect as the basic class), the code is in 181, (2) to solve a complex problem, you want to create a class to assist your program, and do not want to expose it. Create an internal class inside the method, or you can create an internal class in any range, but the internal class can only be used within the internal class, and the external class cannot be called. There are also anonymous internal classes, which are not very clear about how to use them correctly. An important feature of an internal class is that it can range the encapsulated private member variables in the class. It is also important that the object of the internal class holds an object handle of the encapsulated class that creates it by default.

 

16. A particularly effective rule when building the constructor: The simplest way is to make the object ready, and if possible, avoid calling any method, the only method that can be safely called in the builder is the attribute method with final in the base class (private or optional, automatically final). These methods cannot be overwritten, it is not affected by subclass (the base class constructor calls the abstract method in this class to initialize the object, but this abstract method has been overwritten by the quilt class, when the constructor of the parent class is called, The method overwritten by the quilt class is automatically called according to the dynamic binding principle, so that the object may not be correctly initialized ).

 

17. If you can use the base class to call all the methods of the subclass in the "", you must ensure that the subclass only contains all the methods of the base class and does not include any additional methods. In this case, we must use a "downsampling style" to call additional methods of sub-classes, but "upsampling style" must be safe, because the basic class cannot have a larger interface than the category class, therefore, each message category sent by the basic class can be accepted, but the "downsampling style" will not work.

 

 

 

 

 

 

 

Chapter 8: Object Storage

 

1. array: length only indicates the number of elements or handles that the array can hold. It does not know the actual number of elements. The access speed of the array is faster than that of the Collection class, but other operations are not feasible and not flexible enough, the size of the array must be determined in advance. Once created and initialized, the elements in the array cannot be deleted, so that the occupied memory cannot be released.

 

2. collection class: when the model is not used, the collection class cannot control the type of objects placed in the Set, because the collection class defines a root type object, however, if the object to be put into the set is not of the same type, an error will be reported when the collection class object is retrieved, the type of the object stored in the control set is to put the set into a method. The parameter of this method is the type of an object, and then the object is saved to the set, this ensures that only one type of object is stored in the collection; otherwise, an error will be reported during compilation.

 

3. STACK: meets the "first-in-first-out" principle, that is, the first-in-first-in objects in the stack should be retrieved first.

 

4. Comparison of arraylist and sorted list: It is highly efficient to traverse the elements and insert and delete operations of a set in order, while arraylist is highly efficient to randomly access elements in a set.

 

5. hashset and arrayset. We select hashset by default. Similarly, in map selection, we select hashmap first.

 

6. java provides two static classes to sort and search arrays or lists. arrays is used for arrays and collections is used for lists, collections has a control list and other attributes that cannot be modified by the set. This is very important, so that we can set a container to private, then, write a method to return an unchangeable container class handle, so that you cannot modify the elements in the container, but can still modify the content in the class. Another static method is to control the synchronization of the container class, called synchronizedcollection,

 

7. The keyword instanceof tells us whether the object belongs to a specific type of instance. The returned value is a Boolean value, such as if (x instanceof dog) {(DOG) X. Bark ()};

 

 

 

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.