[Java Learning notes] Java Core Technology Vol. 1 the fourth chapter

Source: Internet
Author: User

The basic concepts of Class 4.1 and object in the 4th chapter

Describes the basic concepts of classes and objects, and describes the relationships between classes.

Many of the objects in the program come from the standard library, and some are custom.

Structured programming: Through the design of a series of processes (algorithms), choose the right storage way to solve the problem. Algorithms + Data Structures

4.1.1 class/Package/Inheritance

A class is a template for constructing objects, and the process of constructing an object by a class is called creating an instance of the class.

Encapsulation: Also known as data hiding. Formally, encapsulation is simply a combination of data and behavior in a package, and the user of the object hides the way the data is implemented. Advantages 4.2.3

Instance field: The data in the object.

Method: The process of manipulating the data.

There is a specific set of instance domain values for each particular object. The collection of these values is the current state of the object.

The key to implementing encapsulation is in an instance domain with absolutely no way to allow methods in the class to directly access other classes. A program interacts with object data only through the methods of the object. This is the key to improving reusability and reliability.

Inheritance: By extending a class to create another new class.

When extending an existing class, this expanded new class has all the properties and methods of the extended class.

A source file in Java can contain only one public class and the file name must match the common class.

Properties of the 4.1.2 object

The behavior of the object: The method of the object. All object instances of the same class, with the same method, get a family-like similarity.

The state of the object: how the object responds when the method is used. The state of the object describes the characteristic information of the current object, and the state can only be changed by invoking the method (otherwise the encapsulation is compromised).

Object identity: The state of an object does not fully describe an object. Each object has a unique identity.

The relationship between 4.1.3 classes

Dependency: Use-a, the method of Class A manipulates the object of Class B, and a relies on B. The least mutual dependence, the least coupling degree.

Aggregation: Has-a, an object of Class A contains an object of Class B.

Inheritance: Is-a, General to special,

Use UML to draw class diagrams that describe the relationships between classes.

4.2 How to use Class 4.2.1 Objects and object variables

All Java objects are stored in the heap.

Constructs and initializes an object using the constructor.

An object variable does not contain an object, and the value of an object variable is simply a reference to an object stored elsewhere. The return value of new is also a reference. When an object contains another object variable, the variable still contains only a pointer to another heap object.

(reference equivalent to pointer, memory address)

New The date ();D ate dead=null, andif dead=date, dead references the same object as date.
4.2.2 Discourage use of methods

When the Class library designer realizes that a method should not exist, it is marked as discouraged, and although it is still available in the program, a warning appears at compile time and may be removed in a future class library version.

4.3 design class 4.3.1 constructors

Access level: Methods can access the private attributes of the owning class.

Constructor: With the same name as the class, at least one, no limit on the number of parameters, no return value, always using the new operation to invoke.

4.3.2 Instance Domain

Make all data fields private, while setting accessors and modifiers to access and modify data fields.

The benefits of a private data domain, a public change, and an accessor are encapsulated:

1: Can change the internal implementation, except the method of the class does not affect the other code

2: The Change method can perform error checking

If the accessor is to return a reference to a Mutable object, it needs to clone the object first and then return the cloned object. As in the following cases

Employee em= ...; Date d= em.getdate (); GETDATE returns a private Date object in EM as an accessor, but D also references the same object, and the D operation can change the value in EM, destroying the encapsulation.

Final instance Domain

You can define an instance field as final, you must initialize the object when you build it, and you cannot modify it in subsequent operations.

The final modifier is mostly applied to the fields of the base type or the immutable class (each method in the class does not change its object, such as the String Class)

4.3.3 method

The external method is set to public, and the helper method within the class is set to private.

For the designer of the class, the public method must not be deleted, because the other code may be accessed, the private can be deleted

4.3.4 static domain

When a domain is defined as static, there is only one such domain in the class, and each object shares a static domain, even if no object domain exists, and it belongs to the class that does not belong to the object. Accessed using the class name. Math.PI

Static constants: public static final double PI, static constants are not modified, so set to public

4.3.5 static method

Used by a class and cannot be used on an object.

The instance domain cannot be accessed in a static method because the static method cannot manipulate the object. However, you can access the static domain in the class.

When a method does not need to access the state of an object, its parameters are provided by displaying parameters or simply accessing a static field in the class can be set to a static method.

L Factory Method

A use of static methods.

such as Numberformat.getcurrnecyinstance (); Numberformat.getpercentinstance ();

The constructor cannot be named, and the name of the constructor must be the same as the class name, but there are different names when you want the currency instance and the percentage.

The constructed object type cannot be changed when the constructor is used.

4.3.6 Method Parameters

Call by value: receives the value provided by the caller; Call by reference: receives the variable address provided by the caller.

Method can modify the value of a variable that corresponds to a passing reference, and cannot modify the value of a variable that corresponds to a pass-through value invocation.

Java is always called by value. All the parameter values obtained by the method are a copy, the object reference and other copies refer to an object at the same time, and the method cannot modify the contents of any parameter variables passed to it.

"Reference" is a "value" that requires memory a to store, the parameter of the method gets a copy of the value stored in the new memory B, memory B is discarded after the method ends, and the value in the original memory A is still not changed.

The parameters used in the method and the passed parameters store the same "reference" value in different memory, which points to a memory block, which actually records the values of each instance field in the object, the "reference" of the parameter used in the method uses the change, the value in the memory block is changed, the original "reference" It also points to the memory block that the storage content has changed, so it realizes the state of changing the object parameters.

 Public Static void Swap (employee X,employee y) {   employee temp=x; x=y;y=temp;} The two objects that are passed in are not exchanged. Because X and y do not reference the original object, but instead copy the original object's "value (address)", the interchange is X and y even if the swap (int x,int y) will not succeed.

4.4 Object Constructs 4.4.1 Overloads

Multiple methods have the same name and different parameters. The method name and parameter type are called method signatures.

The return type does not belong to the method signature and cannot have two methods with the same name and the same parameter type but return different types of values.

4.4.2 Default Domain initialization

If you do not explicitly assign an initial value to a domain in the constructor, the domain is automatically assigned the default.

The local variable must be explicitly initialized, and the domain will be automatically initialized to the default value if it is not initialized.

4.4.3 constructor with no parameters

When an object is created by a parameterless constructor, the state is set to the appropriate default value.

The system provides a default constructor only when no constructors are provided in the class. That is, if a constructor with parameters is provided without parameters, the system does not automatically provide a constructor without parameters, and an error occurs when using a constructor with no parameters.

4.4.4 Display domain initialization

It is a good design practice to make sure that the constructor is invoked anyway, and that each instance domain can be set to a meaningful initial value.

The initial value is not necessarily a constant. You can invoke a method to initialize a domain.

4.4.5 calling another constructor

The first statement of the constructor is shaped like this (...), which invokes another constructor of the same class, in parentheses as a parameter list, and according to the parameters, which constructor is selected.

 Public Employee (double
  calls Employee (string,double) ...
This ("", s);
...
}
4.4.6 initialization block

In a declaration of a class, you can include multiple blocks of code that are executed as long as the objects of the class are constructed. Such as:

Class employee{
int NextID;   int ID; private// initialize block public Employee () ... Public Employee (String s,int i) ...} Executes the ID=NEXTID code block, regardless of which constructor is executed
Processing steps for the 4.4.7 constructor

Based on the steps in these multiple ways:

1: All data fields are initialized to default values.

2: Point to all domain initialization statements and initialization blocks in the order in which they appear in the class declaration.

3: If the first row of the constructor calls the second constructor, the second constructor principal is executed.

4: Executes the body of this constructor.

4.4.8 Object Destruction

Java has automatic garbage collection and does not support the destructor.

The Finalize method is called before the garbage collector clears the object, and in practice do not rely on using the Finalize method to reclaim any scarce resources because it is difficult to know when this method will be able to be invoked.

For resources (such as files) that need to be closed immediately after use, apply the Close method to complete the cleanup operation when the object is exhausted.

4.5 Packs

Java allows classes to be organized using packages, while ensuring the uniqueness of class names.

To guarantee the absolute uniqueness of the package name, Sun recommends that the company's Internet domain name be used in reverse order as the package name. and use different sub-packages for different projects.

Import of the 4.5.1 class

The Java.lang package is imported by default.

A class can use all the classes in the owning package, as well as the public classes in other packages.

Import a specific class or an entire package, such as an import java.util.*, using the import statement;

Import java.util.* and import java.util.Date; There is no negative effect on the size of the code.

Use an asterisk to import only one package, not all packages prefixed by it.

In most cases, only the required packages are imported, but need to be considered when naming conflicts occur. If you use only one, you can import that one precisely, otherwise the full package name is prepended to the class.

The only benefit of the import statement is convenience.

Source–organize Imports Pagckage in eclipse

4.5.2 Static Import

Import not only imports classes, it also imports static methods and static fields.

such as import static java.lang.system.*; The Out.println (...) can be used directly;

4.5.3 putting classes in a package

At the beginning of the source file, write the package name;

Scope of the 4.5.4 package

Variables Show Private,

Classes, methods, and variables can be accessed by all methods in the package without setting the access modifier.

The package sealing mechanism mixes the various packages and can no longer add classes to this package.

4.6 Class Path

The class is stored in a subdirectory of the file system. The path to the class must match the package name.

Class files can also be stored in a jar (Java archive) file. In a jar file, you can include more than one compressed form of class files and subdirectories.

To enable a class to be shared by multiple programs, the following points are required:

1: Put the class in a directory, which is the base directory of the package tree structure.

2: Place the jar file in a directory

3: Set the classpath. The Classpath is a collection of all the paths that contain the class file. Base directory/current directory/jar file

The compiler locates the file, and if a class is referenced without spending the package in which the class resides, the compiler first looks for the package that contains the class and inquiries all imports to determine if it contains the referenced class. If more than one class is found, a compilation error occurs, the class must be unique, and the order of the import statements does not matter.

Then also to see if the source file is newer than the class file, and if so, the source file will be automatically recompiled. Because only the public classes in other packages can be imported, and a source file contains only one common class, the compiler is easy to locate the source file. If a class is imported from the current package, the compiler will search all source files in the current package to determine which source file defines the class.

4.7 Documentation Notes 4.7.1 Inserting of comments

Javadoc, you can produce an HTML document from a source file. Javadoc utility extracts information from the following features:

Package

Public classes and interfaces

Public and protected constructors and methods

Public and protected domains

The comment begins with/** and ends with */. Free-form text. Mark starts with @

4.7.2 class Comments

Class comments must be placed after import, before the class definition.

4.7.3 Method Comments

The method comment must precede the described method, and the following markup can be used in addition to the generic tag

@param variable description can occupy more than one line, you can use HTML tags, but all @param tags of a method must be put together

@return describes adding a return section to the current method, which can be used to use HTML tags across multiple lines

@throws class Description This tag adds a comment that indicates that the method might throw an exception. 、

4.7.4 Field Comment

You only need to create a document for the public domain (usually only static constants)

4.7.5 General Notes

The following can be used in comments in a class document

@auther Name

@version version

@since started in

Add comments that are no longer used @deprecated classes, methods, variables, and so on

@see references are used in classes, methods, and add a hyperlink.

4.7.6 Package with overview notes

Classes, methods, and variable annotations can be placed directly in the Java source file, as long as the/**. */For the world. However, to generate the package annotations, you need to add a separate file in each package directory:

1: Provide an HTML file named package.html, all the text in the body will be extracted

2: Provide a Java file named Package-info.java, this file must contain an initial with/**. */For the defined Javadoc annotation, followed by a package statement. It should not contain more code or comments.

You can also add an overview comment for all source files, placed in a file named Overview.html, and included in the parent directory of all source files. All text in the body will be extracted.

Class 4.8 Design Tips

1: Be sure to keep your data private

2: Be sure to initialize the data

3: Do not use too many basic types in the class

4: Not all domains need to set up separate domain accessors and domain changes

5: Decompose a class with too many responsibilities

6: Class name and method name to be able to reflect their responsibilities

[Java Learning note] Java Core Technology Vol. 1 fourth

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.