[Think in Java] Foundation supplements 1-object initialization, garbage collector, inheritance, composition, proxy, interface, abstract class

Source: Internet
Author: User
Tags instance method

Directory

Introduction to the first chapter object
Chapter II Everything is the object
Chapter Three operator
The fourth chapter controls the execution process
Fifth chapter initialization and cleanup
The sixth Chapter access rights control
Seventh re-use class
Nineth Chapter Interface

Introduction to the first chapter object

1. Where is the data of the object located?

There are two ways of storing objects in memory:

(1) In pursuit of maximum execution speed, the object's storage space and life cycle can be determined when the program is written, which can be achieved by placing the object in a stack or in a static storage area. This approach sacrifices flexibility.

(2) Create objects dynamically in a pool of memory called heaps. In this way, knowing the runtime knows how many objects the object needs, their life cycle, and their specific type.

Java uses dynamic memory allocation in its full form. Whenever you want to create a new object, use the New keyword to build a dynamic instance of this object.

2. The life cycle of an object

For languages that allow objects to be created on the stack, the compiler can determine how long an object will survive and automatically destroy it. Not for objects created on the heap. Java provides a garbage collector to destroy objects that are no longer in use.

Chapter II Everything is the object

1. Manipulating objects with references

Each language has its own way of manipulating memory elements. (1) Direct manipulation of element (2) indirect operations (such as pointers in C and C + +).

In Java, the following declaration: String s; Simply means that a reference to a string object is declared in the stack. Similar to the following in C + +: string *s;

2. Exceptions: Basic types

For the base type, Java uses the same approach as C + +. Instead of creating a variable with new, you create an "automatic" variable that is not a reference. This variable stores the " value " (not the object's reference) directly and places it on the stack .

A basic type of wrapper class that allows you to create a non-basic object in the heap that represents the base type for.

All numeric types in Java have a sign and no unsigned integer type.

Two classes of high-precision calculations: BigInteger and BigDecimal.

3. Static

Non-static methods are associated with specific objects that implicitly have the this pointer executing the current object, so the non-static method either accesses the object's domain or modifies the object's domain. The static method, because there is no this pointer, does not access any objects of the object and is not associated with a specific object.

4. The Java.lang package is imported into each Java file by default.

5. Ant commands and Build.xml are similar to make and makefile files.

Chapter Three operator

1. Assignment operators and reference types

Assigning an object to another object is actually copying the reference from one place to another. This differs from the assignment operator in C + +, where the class controls the specific semantics.

This leads to a special phenomenon: "aliasing phenomenon".

2. Random class

If the random class object does not pass arguments at the time of creation, the current time is the seed of the random number generator by default, so that any use run will produce a different sequence of random numbers. If a specific parameter is passed as the seed of the random number generator, the same sequence of random numbers is produced for each run.

3. Relationship operators and reference types

Relational operators compare the relationships between the operands ' values . For reference, it is a reference to the comparison object, even if the value of the object is the same. To compare the size of the object's field, overwrite the Equals method of the objects class, note that the default behavior of equals is to compare references.

4. Unlike C/c++,java, a non-Boolean value can not be used as a Boolean value in a logical expression.

5. Shift operation

Left 0, right Shift two: (1) Signed right Shift (>>): Follow the symbol extension (negative 1, positive 0), (2) Unsigned Right Shift (>>>): both positive and negative, both in the high-up 0.

6.float and double are always not fractional when transitioning to integers. To be rounded, call the Java.lang.Math.round () method.

The fourth chapter controls the execution process

1. The static method in the math library random () is used to produce a double value between 0 and 1 (including 0, excluding 1).

2. The foreach syntax is used for arrays and containers and can also be used with iterable objects.

Fifth chapter initialization and cleanup

initialization and cleanup are just two issues that involve security .

1. Constructors

When an object is created, the constructor is called by the compiler, which guarantees that it has been properly initialized before the object is invoked (the method that called the object).

2. Method overloading

Methods for Differentiating method overloads: Differentiate by parameter list (by the type, number, and order of the parameters). )

Note: It is not feasible to differentiate method overloads by the return value.

3. This keyword

In an instance method: Represents a reference to the object that called the method.

To call the constructor in the constructor:

(1) In a constructor, only one call to another constructor can be made through this, and it cannot be called more than once.

(2) constructor calls must be placed at the very beginning.

4. Finalize and garbage collection

Is there a garbage collector, and why do you care about cleaning?

The Java garbage collector knows only to release the memory allocated by new. Sometimes an object obtains a "special" area of memory (not using new), and the GC does not know how to release the "special" Memory of the object.

Solution: Java allows you to define a method named Finalize () in a class. It works as follows: Once the GC is ready to release the storage space occupied by the object, its finalize () method is called first, and the memory occupied by the object is actually reclaimed when the next garbage collection action occurs.

Note: Finalize () differs from destructors in C + +. In C + +, objects are bound to be destroyed, and objects in Java are not always garbage collected. In other words: (1) The object may not be garbage collected. (2) Garbage collection is not equal to "destruction". (3) Garbage collection is only related to memory.

The reason for Finalize () is that it is possible to allocate memory in a way similar to the C language, rather than the usual practice in Java. This situation occurs primarily when using the local method.

Remember: neither "garbage collection" nor "Finalize" is guaranteed to happen.

System.GC () is used to tell the JVM to run the garbage collector.

One of the possible uses of finalize: we want to ensure that an object should be in a certain state (termination condition) before it is cleaned, then you can verify that the object is in that state by validating it in the Finalize method. P89 Exercise 12.

More Finalize uses refer to "effective Java".

5. How the garbage collector works

Garbage collection mechanism:

(1) Reference count

BUG: Handling circular references is cumbersome.

Meaning: Just to illustrate how garbage collection works, has never been applied to any kind of JVM implementation.

(2) from the stack and the static storage area, traverse all references to find all the surviving objects.

The garbage collector in the JVM is: "Adaptive, generational, stop-copy, Mark-clean", type garbage collector.

6. Sequence of initialization

Summarize the object creation process, assuming there is a class named dog:

(1) Even if the static keyword is not displayed, the constructor is actually a static method. Therefore, when you first create an object of type dog (the constructor can be considered a static method), or when the static method/static domain of the dog class is first accessed, the Java interpreter must look for the classpath to locate the Dog.class file.

(2) then load Dog.class (a class object will be created here), and all actions related to static initialization will be executed. Therefore, static initialization is done only once when the class object is first loaded.

(3) When you create an object with new dog (), you will first allocate enough storage space on the heap for the Dog object.

(4) This storage space is zeroed, which automatically sets all the basic data types in the dog object to the default values (0 for the number, the same for bool and char), and the reference is set to NULL.

(5) Performs all initialization actions that appear at the field definition.

(6) Execute the constructor. (There are a lot of actions involved when it comes to inheritance.)

Tips: The constructor is also the static method, although the static keyword is not written in the display. You can then summarize the load time of a class by saying that the class is loaded when any of its static members are accessed.

7. Arrays

The initialization of an array can use a special expression, as follows:

Int[] A = {1,2,3,4,5};

Note: In this case, the allocation of the storage space will be the responsibility of the compiler. This approach is allocated in heap space (equivalent to using new) rather than stack space, which differs from C + +. And the copy of the array is simply a copy of the reference.

8. Enum

Enumeration types are actually classes and have their own methods. such as ToString (), static values (), ordinal () method, and so on, the enum type can also be used within the Swtich statement.

The sixth chapter access rights control

How to distinguish between things that change and things that remain unchanged.

1. The level of access in Java is from large to small: public,protected, package access (no keywords), and private.

2. Each Java file becomes a compilation unit, and there can be only one public class in a compilation unit.

3. class file Lookup path: Starting with the directory specified by the CLASSPATH environment variable, the JVM obtains the name of the package and replaces each period with a backslash to produce a path name from the Classpath root.

seventh re-use class

Two code reuse mechanisms: Combination & Inheritance

1. Combination

Combination: You only need to place the object reference in the new class. If you want to initialize a reference to a placed object, you can do so at the following location in the code:

(1) Where the object is defined. This means that they are always able to be initialized before the constructor is called.

(2) In the constructor of the class.

(3) This is an inert initialization before the objects are being used. This approach reduces the additional burden of generating objects that are not worthwhile and do not have to generate objects every time.

(4) Use instance initialization (the way it corresponds to static block initialization).

2. Inheritance

When inheriting a class, the subclass automatically gets all the fields and methods in the parent class, except that there are no access rights to the domain or method.

A subclass object consists of two parts, which inherit the part of the parent class and the subclasses that are unique to the subclass. Therefore, the constructor of the parent class should be called in the constructor of the subclass, and then the construction of the sub-class part is executed.

If we do not explicitly invoke the constructor of the parent class, the Java compiler automatically inserts a call to the parent class default constructor in the child class's constructor. If the parent class does not have a default constructor or if we want to invoke a parent class constructor with parameters, you must explicitly write the statement that invokes the parent class constructor with the keyword super.

3. Agent

Java does not provide direct support for it, which is the middle of the middle between inheritance and composition. Because we put a member object in the class we want to construct (like a combination), at the same time we expose all the methods of that member object (like inheritance) in the new class.

Combination: The emphasis is on reusing the functionality of the placed class, rather than being placed in the form of a class (that is, not necessarily exposing the interface that is placed into the class).

Inheritance: Calls to inherit the form (interface) of an existing class and add new code.

4. Name Masking

If the parent class of Java has a method name that has been overloaded multiple times, redefining the method name in the subclass does not mask any version of it in the parent class (this is different from C + +).

5. Choose between composition and inheritance

Combinatorial techniques are typically used in situations where you want to use the functionality of an existing class in a new class rather than its interface.

At the time of inheritance, use an existing class and develop a special version of it.

The relationship of "has-a" is expressed by combination, and the relationship of "is-a" is expressed by inheritance.

The clearest way to use composition or inheritance is to determine whether you need to move up from the new class to the base class. If so, inheritance is necessary, otherwise it should be considered whether inheritance is required.

6. Final keyword

When modifying data:

(1) An immutable constant compilation constant. In Java, such constants must be basic data types and are final decorated (not necessarily static adornments).

(2) A value that is initialized at run time, and we do not want it to change.

When final is applied to an object reference, rather than to the base type, the final causes the reference to be the same, not the referenced object. In addition, the final modified data does not represent compile-time constants, such as (2).

When modifying parameters:

If the argument is also a reference type, it means that the value of the reference itself cannot be modified, rather than the value of the object pointed to by the reference. That is, for parameters of a reference type, even the final decoration, you can change the value of the object that the reference points to.

7. Inheritance and initialization

The constructor is also the static method, although the static keyword is not written in the display. You can then summarize the load time of a class by saying that the class is loaded when any of its static members are accessed. Object creation Process:

(1) The parent class static members and static initialization blocks are executed sequentially in the order in which they appear in the code.

(2) A subclass static member and a static initialization block, executed sequentially in the order in which they appear in the code.

Now that the class is loaded, you are ready to create the object:

(3) Allocate enough storage space on the heap for the object and initialize it to binary 0.

(4) Instance members and instance initialization blocks of the parent class, executed sequentially in the order in which they appear in the code.

(5) Executes the construction method of the parent class.

Now that the parent part of the object of the heap space is initialized, the subclass section is initialized:

(6) Subclass instance members and instance initialization blocks, executed sequentially in the order in which they appear in the code.

(7) The constructor method of the subclass is executed.

Note: If a polymorphic method is called in the parent class constructor in (5), the problem occurs at this point. Therefore, avoid calling other methods in the constructor. Details p163

Nineth Chapter Interface

1. Abstract class

Classes that contain abstract methods are called abstract classes. Or it may not contain abstract methods (as if it makes no sense), as long as the class is decorated with an abstract.

Abstract classes are useful tools for reusing, making it easy to move public methods upward along the inheritance hierarchy.

Abstract classes cannot be instantiated, and the compiler will make an error.

2. Interface

An interface means "all classes that implement that particular interface look like this." Interfaces are used to establish the protocol between classes.

The fields contained in the interface are implicitly static and final.

If a method operates on a class other than an interface, then the class and its subclasses can only be used, not a class that is not in this inheritance architecture.

3. Selection of abstract classes and interfaces in Java

    • Java does not support multiple inheritance, you can use interfaces when you need to inherit multiple classes, for example: thread and runnable;

    • interface-oriented programming (programming for interfaces) is one of the object-oriented design principles and should be oriented towards interface programming;

    • abstract class is more suitable for code reuse, avoid writing duplicate code, example: List interface has a abstractlist implementation, avoid ArrayList and LinkedList implementation list when some code to repeat; (with 51 meanings)

    • interfaces are more loosely coupled than abstract classes. Because there can be implementations of public methods in the abstract class;

    • Interfaces help implement a dependency injection (Dependency injection) design pattern, for example: Spring framework.

Reference: When to use interface and abstract class in Java

[Think in Java] Foundation supplements 1-object initialization, garbage collector, inheritance, composition, proxy, interface, abstract class

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.