Thinking in Java notes (chapter II everything is an object)

Source: Internet
Author: User

Chapter II Everything is Object 2.1 manipulating objects with references

Each language has a way of manipulating the elements in memory, and it must be aware of what data type is being processed, whether it is manipulating the elements directly or based on some kind of special syntactic indirection (such as pointers in C and C + +) to manipulate objects.

Everything in Java is treated as an object and can be used with a single fixed syntax, but the identifier manipulated by the programmer is actually a "reference" to the object, which can be either independent of the object or associated with the actual object. For example:

String s1;String s2 = new String("hello world");

The S1 above is a self-contained reference (a null reference), and S2 is a reference associated with the actual object. If a message is sent to a null reference, a run error is returned.

2.2 Creating objects

After you create a reference, it's a good idea to associate it with a new object. It is usually implemented with the new operator.

2.2.1 Storage location

When the program runs, there are five different places to store the data:

    1. registers the fastest storage area, located inside the processor, but limited in number, needs to be allocated according to requirements, cannot be directly controlled, in C and C + + can be recommended to the compiler to store data to register.
    2. The stack speed is second only to register, in RAM, through the stack pointer can be accessed directly from the processor, the pointer moves down to allocate new memory, the pointer moves up to free memory. When you create a program, the Java system must know the life cycle of all the items in the stack, facilitate the management of the storage space, the Java data exists in PvP, especially the object reference, but the Java object is not here.
    3. Heap A common memory pool, located in the Ram area, for storing Java objects. The benefit of a heap different from a stack is that the compiler does not need to know the life cycle of the data in the heap. So there's a lot of flexibility, but the price for flexibility is that memory allocation and cleanup takes more time than stacks
    4. constant Storage constant values are usually stored directly inside the program code, which is safe because constants are never changed, and sometimes the constants in the embedded system are separated from the rest, in which case you can choose to place the constants in the ROM.
    5. non-RAM storage If the data exists outside of the program, it is not controlled and is independent of the program. Two of the basic examples are Stream objects and persisted objects . In a stream object , the object is converted into a byte stream, which is usually sent to another machine. persisted objects , the object is stored on disk, so even if the program terminates, the data can still maintain its own state.
2.2.2 Exceptions: Basic types

A series of types are often used in programming, requiring special treatment because new creates an object with new--especially small, simple variables that are not very effective--because they are stored in the heap. Therefore, for these types, Java takes the same approach as C and + C. That is, instead of creating a variable with new, you create a non-reference "auto" variable directly. This variable stores "values" directly on the stack and is therefore more efficient.

Java to determine the amount of storage space that each base type occupies. The size does not change as the hardware changes with other languages. The immutability of this storage space is one of the reasons why Java portability is strong.

Base type size minimum maximum wrapper type

Boolean none None None Boolean

Char 16-bit Unicode o Unicode 2^16-1 Character

BYTE 8 bits-128 +127 byte

Short 16bits-2^15 +2^15-1 Short

int bits-2^31 +2^31-1 Integer

Long 64bits-2^63 +2^63-1 Long

float + bit IEEE754 IEEE754 float

Double 64bits IEEE754 IEEE754 double

void None None of none void

All numeric types have positive and negative numbers, so don't look for unsigned numeric types. The size of the storage space on which the Boolean type is stored is not explicitly stated and is defined only to be able to take true or false. The wrapper class that the base type has makes it possible to create a non-basic object in the heap. For example:

char c = ‘x‘;Character ch = new Character(c);

High-precision numbers

Java provides two classes for high-precision computing: BigInteger and BigDecimal. These two classes, while broadly part of the wrapper class, do not have a corresponding base type. But can be used for int or float operation, also can be used for these two types, but must be in the form of a method call to replace the operator, the operation speed will be slow, with speed in exchange for precision.

BigInteger supports integers of arbitrary precision, that is, an integer value of any size that can be accurately expressed without losing precision.
The BigDecimal supports fixed-point numbers of any precision.

2.2.3 Arrays in Java

Arrays are supported in almost all programming languages. It is dangerous to use arrays in C and C + +, because arrays are blocks of memory. If the program accesses storage space outside of its own memory, the consequences are unpredictable.

One of the main goals of Java is security, which ensures that arrays are initialized and cannot be accessed outside of its scope, which is done with a small amount of memory overhead on each array and a run-time subscript check.

When you create an array, you actually create a reference array, and each reference is automatically initialized to a specific value (NULL). Once Java sees NULL, it knows that the reference exists independently, is not associated with other objects, and if null references are used, the error is returned at run time. This avoids the situation outside the scope of the visit.

2.3 Never need to destroy objects

In most languages, the concept of the variable life cycle is important, and the individual objects need to be destroyed manually, but Java has done that for us.

2.3.1 Scope

Most procedural languages have the concept of scope (scope). The scope determines the visibility and life cycle of the variable names defined therein. C and C + + are also in Java, where the scope is determined by the position of the curly braces:

{    int x = 12;    //到这里为止,x可以访问    {        int q = 96;        //这里x和q都可以访问    }    //到这里x能访问,但q不可以。}

In Java, however, you cannot do the following:

{    int x = 12;    {        int x = 14;    }}

The compiler will report that the X variable has already been defined. So in C and C + + you can "hide" a large scope variable, but not in Java, which Java designers think will cause confusion.

Scope of the 2.3.2 object

Java objects do not have the same life cycle as basic types. When new is a Java object, it can exist outside the scope. For example

{    String s = new String("a String");}

The reference s disappears at the end of the scope. However, the string object pointed to by S still continues to occupy memory space. In this small piece of code, we cannot access this object after this scope because the only reference to it is beyond scope.

Objects created by new are persisted. In this way, many C + + problems disappear completely in Java. In C + +, you must not only ensure that objects are kept as long as you need them, but you must also destroy them after they are not used.

Java has a garbage collector that monitors all objects created with new and identifies objects that are no longer referenced. The memory space for these objects is then freed.

2.4 Creating a new data type: Class

In Java everything is an object, the object should correspond to a type, that is, the "type" keyword, the keyword class is used to denote "I am going to tell you a new type of object", for example:

class ATypeName{}

In this way, a new type is introduced. However, you cannot send any messages to this new type of object.

2.4.1 fields and methods

Once a class is defined (all the work you do in Java is defining classes, creating objects of classes, sending messages to those objects), you can set up two types of elements in a defined class: fields (sometimes referred to as data members) and methods (sometimes called member functions). A field can be any type of object, or it can be one of any basic types. If the field is a reference to an object, the reference must be initialized to prevent the reference from being null.

Normal fields cannot be shared between objects that are created.

class DataOnly{    int i;    double d;    boolean b;}

This class has no other use than storing the data, but it is possible to create a reference to the object. Each base type has a default value, even if the member variable is not assigned a value after the object is created. However, this situation does not occur in non-class fields, such as in the program:

int x;

In this case, the x here does not have a default value of 0, and if you forget to initialize, Java will return an error at compile time. C + + only warns, but Java treats it as an error.

2.5 methods, parameters, and return values

The functions in many languages are the methods mentioned in Java. method determines what kind of message an object can accept. The basic composition of the method includes: name, parameter, return value, and method body. The following are the most basic forms:

ReturnType methodName(/*argument list */) {    /* method body*/}

The method name and parameter list are combined to become "method signatures," which uniquely identify a method. Methods in Java can only be created as part of a class. Methods can be called only through objects.

2.5.1 parameter list

The parameter list of the method shows the information passed to the method, and everything in Java is an object, and the arguments are no exception. Therefore the referenced type must be passed the same as the parameter type.

2.6 Building a Java program 2.6.1 naming problem

The concept of a name control is introduced in C + + with several keywords. Java, for its use, generates names that are not confused with other names, and all sorts of mechanisms mean that all files automatically exist within their name control, and each class in the consent file has a unique identifier.

2.6.2 using other constructs

Using your own pre-defined class, if the defined class is in the same file, Java can be found directly (eliminating the "forward reference" issue). When the class to be referenced is in another file, the compiler is not able to find it intelligently. You need to use the keyword import to tell the compiler exactly what kind of place you need. Import instructs the compiler to import a package, which is a class library (in other languages, a library contains not only classes, but also methods and data, but all of the code in Java must be written in a class, that is, everything is an object).

2.6.3 Static keyword

When you create a class, you are describing the behavior and appearance of the object of that class, unless you create the object of that class with new, and you do not actually get any objects. The storage space is allocated only when new is executed.

However, if you want to assign a single storage space to a particular domain, do not create any objects, or you can invoke a method without creating an object, you need to use the keyword static. When you declare a thing static, it means that the domain live method is not associated with any object instance of the class that contains it. You can also access methods or data that are declared static to create objects. Consider the following example:

class StaticTest{    static int i = 47;}StaticTest st1 = new StaticTest();StaticTest st2 = new StaticTest();

The above code defines a variable I of type int with the static keyword in a class, even if two objects of that class are created, and the STATICTEST.I variable has only one copy of the storage space, both of which share the same i. There are two ways to reference a static variable:

    • To locate through objects, such as st1.i.
    • Directly referenced by the class name, such as Statictest.i

Obviously the latter way is better, emphasizing the static structure.
Static methods are similar.

2.9 Coding Style

In the Java programming language coding conventions, the code style is as follows: The first letter of the class name should be capitalized, if the class name consists of several words, then put them together, do not use underscores separate, where each inner word of the first letter capitalized, this style is called "Hump." The first letter of the variable is lowercase.

Thinking in Java notes (chapter II everything is an object)

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.