[Java Study Notes] Chapter 4 of Java core technologies

Source: Internet
Author: User
Tags call by reference

[Java Study Notes] Chapter 4 of Java core technologies

 

 

Chapter 5 basic concepts of objects and classes 4th and objects

Describes the basic concepts of classes and objects and the relationship between classes.

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

Structured Program Design: design a series of processes (algorithms) and select an appropriate storage method to solve the problem. Algorithm + Data Structure

4.1.1 class/encapsulation/Inheritance

A class is a template for constructing an object. The process of constructing an object by class is called creating an instance of a class.

Encapsulation: Also known as data hiding. In terms of form, encapsulation only combines data and behavior in a package, and hides the data Implementation Method for the object user. Advantage 4.2.3

Instance domain: Data in the object.

Method: manipulate data.

Each specific object has a set of specific instance domain values. The set of these values is the current state of the object.

The key to encapsulation lies in and definitely cannot allow methods in the class to directly access the instance domains of other classes. The program only interacts with the object data through the object method. This is the key to improving reusability and reliability.

Inheritance: extends a class to create another class.

When an existing class is extended, the new class after expansion has all attributes and methods of the extended class.

In Java, a source file can only contain one public class and the file name must match the common class.

4.1.2 Object Features

Object behavior: Object method. All object instances of the same class have the same method to obtain family-style similarity.

Object status: How the object responds when a method is used. The object state describes the feature information of the current object. The state can only be changed by calling a method (otherwise, encapsulation is damaged ).

Object ID: the object state cannot completely describe an object. Each object has a unique identity.

4.1.3 relationship between classes

Dependency: use-a: Class A's method is used to manipulate Class B's objects. A depends on Class B. The minimum degree of mutual dependency and the minimum degree of coupling.

Aggregation: has-a. Objects of Class A include objects of Class B.

Inheritance: is-a, generally special,

Use UML to draw a class diagram and describe the relationship between classes.

4.2 How to Use objects and object variables in class 4.2.1

All Java objects are stored in the heap.

Use the constructor to construct and initialize the object.

The object variable does not contain an object. The value of the object variable is only a reference to an object stored elsewhere. The return value of new is also a reference. When an object contains another object variable, this variable still contains only pointers pointing to another heap object.

(Reference is equivalent to pointer, memory address)

Date date = new Date (); Date dead = null; if dead = date, dead references the same object as date.
4.2.2 methods not encouraged

When the class library designer realizes that a method should not exist, it is marked as not encouraging. Although it can still be used in the program, a warning will appear during compilation, it may also be deleted in future class library versions.

4.3 design class 4.3.1 Constructor

Access Level: The method can access the private features of the class,

Constructor: it has the same name as the class; at least one; no limit on the number of parameters; no return value; always called using the new operation.

4.3.2 instance domain

Set all data domains as private, and set accessors and implementers to access and modify data domains.

Private data domains, public changers, and accessors are encapsulated, bringing the following benefits:

1: internal implementation can be changed. Other Methods except this class will not affect other codes.

2: The modifier method can perform an error check.

If the accessors want to return a reference to a mutable object, they need to first clone the object and then return the cloned object. In the following cases:

Employee em = ...; date d = em. getDate (); getDate is used as the accessors to return a private date object in em, but d also references the same object. Operations on d can change the value in em and destroy encapsulation.

Final Instance domain

You can define an instance domain as final. You must Initialize an object during Object Construction and cannot modify it in subsequent operations.

Most final modifiers are applied to fields of the basic type or immutable class (each method in the class does not change its object, such as the String class)

4.3.3 Method

The external methods are set to public, and the auxiliary methods in the class are set to private.

For class designers, public methods cannot be deleted, because other code may be accessed and private methods can be deleted.

4.3.4 static domain

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

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

4.3.5 static method

You cannot use an object through a class.

Because static methods cannot operate on objects, they cannot access instance domains in static methods. However, static fields in the hosts class can be used.

When a method does not need to access the object state, its parameters are provided by the display parameter or only the static fields in the response class can be set to the static method.

L factory Method

A usage of static methods.

For example, NumberFormat. getCurrnecyInstance (); NumberFormat. getPercentInstance ();

The constructor cannot be named. The constructor name must be the same as the class name, but different names are used to obtain the currency instance and percentage.

The 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.

You can modify the value of the variable that passes the reference, but cannot modify the value of the variable that calls the passed value.

Java is always called by value. All the parameter values obtained by the method are a copy. The object reference and its copy reference an object at the same time. The method cannot modify the content of any parameter variables passed to it.

"Reference" is A "value" that requires memory A storage. A copy of the "value" obtained by the method parameter is stored in the new memory B, after the method ends, Memory B is deprecated and the "value" in memory A is not changed ".

The parameters used in the method and the passed parameters store the same "Reference" value in different memory. This "Reference" points to a memory block, the memory block actually records the values of various instance domains in the object, and uses the modifier for the "Reference" of the parameters used in the method to change the value in the memory block, the original "Reference" also points to the memory block that the storage content has changed, so the status of object parameters is changed.

Public static void swap (Employee x, Employee y) {Employee temp = x; x = y; y = temp;} does not exchange incoming two objects. Because x and y do not reference the original object, but copy the "value (Address)" of the original object. The exchange is that x and y, even swap (int x, int y) it will not succeed.

 

4.4 Object Construction 4.4.1 overload

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

The return type does not belong to the method signature. There cannot be two methods with the same name and parameter type but different type values returned.

4.4.2 default domain Initialization

If no initial value is explicitly assigned to the domain in the constructor, the default value is automatically assigned to the domain.

Local variables must be explicitly initialized, and fields will be automatically initialized to the default value if they are not initialized.

4.4.3 parameter-free Constructor

When an object is created by the non-parameter constructor, the status is set to the appropriate default value.

The system provides a default constructor only when no constructor is provided in the class. That is to say, if a constructor with parameters is provided without parameters, the system will not automatically provide a constructor without parameters, an error is reported when a constructor without parameters is used.

4.4.4 display domain Initialization

It is a good design habit to ensure that each instance domain can be set to a meaningful initial value no matter how the constructor is called.

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

4.4.5 call another constructor

The first statement of the constructor is like this (...), this constructor calls another constructor of the same class. The parameter list is enclosed in brackets and the constructor is selected based on the parameter.

public Employee(double s){ 
  //calls Employee(String,double)...
  this("Employee ",s);
  ...
}
4.4.6 initialization Block

The declaration of a class can contain multiple code blocks. As long as the class object is constructed, these blocks will be executed. For example:

Class Employee {
Private static int nextID; private int id; private String name; {id = nextID} // initialize the public Employee () block ()... public Employee (String s, int I )..} no matter which constructor is executed, the id = nextID code block will be executed first.
4.4.7 constructor processing procedure

Based on the above steps:

1: All data domains are initialized to the default value.

2: point to all domain initialization statements and initialization blocks in sequence in the class declaration.

3: If the constructor calls the second constructor In the first line, the second constructor is executed.

4: the main body of the constructor.

4.4.8 object structure

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

The finalize method will be called before the Garbage Collector clears objects. In actual applications, do not rely on the finalize method to recycle any shortage of resources, because it is difficult to know when this method can be called.

For resources (such as files) that need to be closed immediately after use, apply the close method when the object is used up to complete cleaning.

4.5 packages

Java allows classes to be organized using packages and ensures the uniqueness of class names.

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

4.5.1 class Import

Java. lang packages are imported by default.

A class can use all classes in the package and the public classes in other packages.

Use the import Statement to import a specific class or the entire package, such as import java. util .*;

Import java. util. * has no negative impact on the code size compared with import java. util. Date.

You can use asterisks to import only one package, not all packages with its prefix.

In most cases, only the required packages are imported, but you need to consider this in case of a naming conflict. If you only use one package, you can import the package accurately. Otherwise, you must add the complete package name before using the class.

The only benefit of the import Statement is convenience.

Source-Organize Imports Pagckage in Eclipse

4.5.2 static Import

Import can not only import classes, but also import static methods and static fields.

For example, import static java. lang. System. *; you can directly use out. println (...);

4.5.3 put the class into the package

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

4.5.4 package Scope

Private variable display,

If no access modifier is set for classes, methods, and variables, all methods in the package can be accessed.

The package Sealing Mechanism blends various packages and cannot add classes to the package any more.

4.6 Class path

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

Class files can also be stored in JAR (Java archive) files. A jar file can contain multiple compressed class files and subdirectories.

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

1: Put classes in a directory, which is the base Directory of the tree structure.

2: Put the JAR file in a directory

3: Set the class path. A class path is a set of all paths that contain class files. Base directory/current directory/JAR File

The compiler locates the file. If a class is referenced without consuming the package of the class, the compiler first looks for the package containing the class and queries all import operations, determine whether the referenced class is included. If more than one class is found, a compilation error occurs. The class must be unique, but the order of import statements does not matter.

Check whether the source file is newer than the class file. If yes, the source file will be automatically re-compiled. Since only the public classes in other packages can be imported, and only one source file contains one common class, the compiler can easily locate the source file. If a class is imported from the current package, the compiler will search all the source files in the current package to determine which source file defines the class.

4.7 insert a document comment 4.7.1

Javadoc, which can produce an HTML document from the 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 starts with/** and ends. Free text. Start @

4.7.2 class annotations

Class annotations must be placed after the import and before the class definition.

4.7.3 method comments

The method annotation must be placed before the described method. In addition to the general Mark, you can also use the following mark

@ Param variable description can occupy multiple rows and can be marked with html, but all @ param tags of a method must be put together.

@ Return Description: adds the return part to the current method. html tags can be used across multiple rows.

@ Throws class description this tag will add a comment to indicate that this method may throw an exception. ,

4.7.4 domain Annotation

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

4.7.5 General Comments

The following are available in the class document Annotations:

@ Auther name

@ Version

@ Since starts

@ Deprecated class, method, and variable add comments that are no longer in use

@ See reference is used to add a hyperlink to a class or method.

4.7.6 package and overview

You can directly comment classes, methods, and variables in the java source file, as long as it is bounded. However, to generate a package comment, you need to add a separate file in each package directory:

1: A package.html-named html file. All text in the body will be extracted.

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

You can also write an overview of all source files, which are placed in an overview.html file and included in the parent directory of all source files. All text in the body is extracted.

4.8 Design Skills

1: Make sure that the data is private

2: Data Initialization is required.

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

4: not all domains require independent domain accessors and domain changers.

5. Break down classes with excessive responsibilities

6: Class names and method names should reflect their responsibilities

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.