Java core technology self-study (b) of objects and classes

This chapter is mainly to explain the object-oriented programming, how to create a standard Java class library objects, how to write your own classes

The face of the program object by objects, each object contains a specific functional part and a hidden part of the user to achieve open, objects in the program, mostly from the standard library, also has its own definition, opp is the data on the first step, then consider the algorithm of operational data, for ideological object is used to solve large-scale problems, to achieve a problem, you might be using 100 classes, each with 20 inside the method to do so we programmer easy to grasp, but also easy to find bug

(1) Class

Class is a template or blue construction objects, we can class as biscuit making machines, and the object is seen biscuit, the process is called the class constructor object instance of the class is created.

Code written in Java are located inside a class

Package: It is an important concept related to the object, it is the combination of behavioral data and then a package inside, hidden objects and user data implementation

Data objects: instance field

Method: operation data

For each specific object has a set of domain specific example, the set of values ​​is the current state of these objects

Key to complete the package is to not let the class method to directly access other types of instance fields, the program only to interact with the number of objects by a method of an object, the package gives the characteristics of the object black box, which is to improve the reusability and reliable the key of (this means that a class can change the way data is stored, as long as the use of a common method, not that other objects will not know or care if it changes)

Inheritance: The OOP Another principle is to make user-defined Java classes easier, it is possible to create another class by extending a class, in fact, all classes are derived from a superclass "Object" class, when a class is extended, this extended class has all the properties and methods of the extended class, as long as the new class of this method is suitable for a new class of data fields can be

(2) Objects

To use OOP, then you need to clear the three main characteristics of the object

Behavior of the object: What can be added to an object

State of the object: When applying those methods, the subject is how to respond to

Identifying the object: how to distinguish different states of the same behaviors and different objects

Change the state of an object must be achieved by calling the method, if you do not change the status by calling the method, then the description of the package was destroyed

Identifying the object always is not the same, the state often there are differences, each object has a unique identity, but also affect the state of the object of its behavior (such as order: "already shipping on orders should reject the method of having deletions of entries ")

(3) identify the class

In object-design program, we should start from the design class, and then to the inside of each method to add columns

Simple rules to identify the class of nouns in the analysis is to find the problem, then the method corresponds to the verb

Just like in order processing system, there is such a term goods, orders, shipping address, which could become a class, while the verb "send", "pay", it may become a method

(4) the relationship between the class

In between classes often have the following relationship:

Dependence: uses - a class if a method of manipulating the objects of another class, then we say that a class dependent on another class, like the Order class uses the Account class, because the Order object needs access to the Account class to see its credit, but we should let the interdependence of classes reduced to a minimum, if a does not know the existence of B, then it will not care about any change of B

Polymerization: has - a like an Order object which contains the Item object, this relationship means that an object contains the object class A class B

Inheritance: is - a common shows a special relationship with such RushOrder Order class inherit from classes, class RushOrder for goods, as well as different methods of calculating shipping priority, while other methods are inherited from the Order class

(5) using a predetermined class

In Java, there is no class you can not get anything done, but not all classes have object-oriented features, like the Math class only encapsulates the function, it does not need to hide data, and therefore do not have to worry about the generated objects and initialize instance fields

1. Object and object variables

To use the object, it is necessary to construct the object, and specifies the initial value, then application of the method object

In the Java language, the constructor used to construct a new instance constructor is a special method, to construct and initialize the object

Constructor should name the class name, the class constructor so named Date Date, Date object to construct a need to add new operator in front of the structure, such as the following

new Date () // This expression constructs a new object that is initialized to the current date and time

If required, you can pass that object a method, or a method may be applied to the object

We also usually desirable to construct the object can be used multiple times, it is necessary to objects in a variable Date birthday = new Date (); we have to distinguish the difference between the object and the object variable, the definition of an object variable, it can refer to the type Date object, as described below

Date deadline; // At this time it is not an object, not actually referenced objects, so in this case the method can not be applied to any variable above Date

You may want to use then you need to initialize the variables, there are two options (1) with the newly constructed object to initialize the variables: deadline = new Date (); (2) to make this variable refers to an object that already exists : deadline = birthday; now two variables refer to the same object

Note: An object does not actually contain a variable object, but merely refer to an object only, the value of any object variable is a reference to an object stored in another place in Java, the return value is a new operator quote

Date deadline = new Date (); // expression new Date () construct an object of type Date, and its value is a reference to the newly created object, a reference in this deadline variable, the variable can be set so the object It is null, indicating that this object variable currently does not reference any object

deadline = null;

If a method of acting on a target null value, then the run-time error is generated, the local variable is not automatically initialized to null, and must be initialized to null or set them by new

The class library 2.java LocalDate

Date class instance has a status, i.e. the specific point in time, time herein refers to a fixed number of milliseconds from the time point, the point is epoch, UTC time which is January 1, 1970 00:00:00, date date class treatment provided and not much use

Library designers decided to save time and give time to name separately, so the library there are two classes, one is used to indicate the Date class point in time, everyone used to indicate a familiar calendar indication LocalDate class method

Time to separate the calendar is a good face design object, usually the last to use a different class to represent different concepts

Do not use the constructor to construct an object LocalDate class, in fact, you should use the static factory method means you use constructors

The LocalDate.now () will be represented by the date when the configuration object, LocalDate newYearsEve = LocalDate.of (1999,12,31) represents the object of a specific date

With the object, you can use the method to get the date, int year = newYearDate.getYear (); \

LocalDate here encapsulate instance field to maintain the set date, based only on the outside to provide a method for service

3. Change the filter method and accessor methods

Changer method: the state of access objects and modify objects

Accessor method: access to the object but does not modify the state of the object

(6) User-defined classes

Before we all learned class with a main method here, let's learn how to set up complicated main classes no main method, have their own instance fields and instance methods, and then if you want to create a complete program, then we need to combine a plurality of classes, wherein class but only a main method

 

1 in which the source file, only that class with a public class name and file name as the source file in which there can be only one public class, but there may be any of the non-public class

 

2. Multiple source files

A source file contains two classes, many people are accustomed to the presence of a separate file for each class, so if you like to organize your files, then compile the program there are two ways:

One is to use a wildcard to call Java compiler

javac Employee * .java, so that all source files with a ratio of the wildcard will be compiled into class files

One is javac EmployeeTest.java

With this, although not explicitly compiled Employee.java file, but when the Java compiler found EmployeeTest.java use the Employee class, it will look for a file named Employee.class, if not found, it will go Employee .java, and then compile it, and more importantly: If Employee.java is updated, then the Java compiler will automatically recompile the file

3. The content parsing class

If a method is marked as public, then that is expressed with any method of any class can call these methods, and instance fields are properly marked as private domain which means that these examples only method available since the class itself access

4 constructor:

For the constructor is configured with the same name as the class, when objects of a class structure, the builder will run to the instance field is initialized to the desired state, the constructor is always accompanied by the new operator is performed calls, and thus not subject to an existing call the constructor for the purpose of resetting the instance fields, the constructor does not return a value, each class can have more than one constructor

Warning: Do not define local variables and instance fields of the same name, defined in the constructor it will lead to those local variables can not be set

The parameters and display parameters implicit

A method for operating an object domain to access their examples, the following is a method call to set the new value

number007.raiseSalary(5)

Examples salary field provided for the above operations, the object of this method calls for the new value, raiseSalary method has two parameters, the first parameter referred to as a hidden parameter (also referred to as a hidden parameter was the method invocation target or recipient) is present in front of the method name Employee class object, the second parameter value is located behind the method name in parentheses, which is an explicit parameter

We can see that the parameters are explicitly listed in the clear statement of the method, the implicit argument does not appear in the method declaration, you can use the keyword this in each method represents an implicit parameters such as the following

public void raiseSalary(double byPercent)

{

double raise = this.salary*byPercent/100;

this.salary+=raise;

}

This allows the local variables and instance fields out significant difference

(All methods in Java must be defined within the class, but it does not mean that they are inline method is not inline method is the task of the Java Virtual Machine)

6. The advantages of packages

If a domain is just a read-only domain, Once set in the constructor, then there is no way to modify it, so you can make sure that this field will not be destroyed outside, if a domain is not read-only domain, then the domain if the problem occurs, then you can use to change is to modify the method can

So sometimes need to get or set the value of an instance field, then it should provide the following

A private data field,

A public domain accessor methods

Change is a public domain method

Do the above behavior after it has the following advantages: (1) we can change the internal implementation, in addition to the methods of this class will not affect other code

As the storage domain name was changed to String firstName; String lastName; then the getName method should be changed to return first + "" + lastName;

The above changes, other programs are totally unable to see (2) to change the methods that can perform error checking, but will not be assigned directly to the domain these processes, such as setSalary ways to check the pay will not be less than 0

 

Note: Do not write variable returns a reference to the object accessor methods, such as the following would be a mistake

public Date getHireDay() {

return Fred;

}

Date object here may vary (it has a changer), which is to break encapsulation

Employee harry = ...;

Date d = harry.getHireDay();

double tenYear = 10*365.25*24*60*60*1000;

d.setTime(d.getTime() - (long)tenYear);

The cause of the error is: d here and harry.hireDay reference the same object, change control method will automatically change the employee's private state

Solution:

To return a reference to a mutable object, then it needs to be first clone, clone objects refers object stored at another position on the copy of the code is modified following:

public Date getHireDay(){

return (Date) hireDay.clone (); // if necessary to return a copy of the data variable, you should use the clone

}

7. Private method

When implementing a class, because the public data is very dangerous, so all data should be set to private, and for the method, most approaches to the public, but in some special cases below (if possible want to calculate the code is divided into a number of independent auxiliary method, these helper methods should not be part of the public interface, it is because they tend and the current implementation mechanism is very close, or require a special agreement, as well as a special calling sequence), where you should buy this set to private methods private

8.final instance fields

Examples of fields can be set to final, this field must be initialized when the object is constructed, that is must ensure that after each structure performs, on the value of this field is set, and it can not be modified later in the operation, i.e. no modifier method, final modifier applied to a base type field or mostly immutable domain (e.g., String, each method will not change their object)

9. static fields, and static methods

Static fields:

If the field is set to static, each class has only one such domain, which means that each object for all instances of domain has its own copy

class Employee {

private static int nextId = 1; // can be directly used when accessing Employee.nextId

private int id;

}

 

Here, each object has its own employee id field, but all instances of this class will share a nextId fields, static fields belong to the class, it does not belong to any separate objects

Static constant:

private static final double PI = 3.145926;

If the static is saved, then it becomes a PI instance field, then you need to access the object through the PI Math class, and each Math object has its own copy, as I said before each class the object can be modified for a total domain, so do not want to field is set to public, but the public may be constant but, since set final, so it is not allowed to modify the

Static method (method of operation can not be implemented to the subject):

The Math.pow (x, a);

The above not to use any Math object, i.e. no implicit parameter is not considered a static method of this parameter, static methods can not access the class Employee Id instance fields, because it is not the operation target, but the method can access its own static static domain

public static int getNextId(){

return nextId;

}

You can be invoked through the class name of this method Employee.getNext (); (we can call the static method by using an object, but this way it is easy to misunderstand, because irrespective of the results and the object of this method, we use our best class name to call static methods)

Use static methods in the following two cases:

(1) The method does not require access to a state of the object, its required parameters are provided by the explicit parameter (Math.pow ())

  (2) a method need only access the class static fields

10. The method of plant

There is also a static method of use, is to use the static factory method to construct the object, as above, we know LocalDate.now () and LocalDate.of ()

Without using the constructor to complete the reasons for this operation:

The constructor can not be named because the constructor's name and class need the same name, but we sometimes need to use a different name

When using the constructor, we can not change the type of object constructed, using construction methods, sometimes we may choose to return to their sub-class type

11.main method

Object main method does not operate any object, in fact, when you start the program does not have any objects, static main method will execute the program and create the required (each class can have a main method, which is commonly used for a classes skills test units)

(7) Method Parameters

In programming, there are some terms on the parameters passed to the method

Passed by value (call by value) value of representations received is provided by the caller

Passed by reference (call by reference) representation received is the variable address supplied by the caller

The method can modify a reference value corresponding variable transmission, but can not change the variable value corresponding to the call transfer value

Java always call by value, that is the method to get a copy of all parameter values, in particular the method can not be passed to modify the contents of any of its parameter variables

Such as

double percent = 10;

harry.raiseSalary(percent);

After the method call, percent values ​​or 10

There are two types of method parameters:

Basic data types and object reference type

From the above we can know that a method can not modify a basic data type parameters, but not the same object reference as a parameter, such as the following operations can be increased to twice the salary

public static void tripleSalary(Employee x) {

x.raiseSalary(200);

}

Called when

harry = new Employee(..);

tripleSalary(harry);

The implementation process as follows:

1) x is initialized to harry worth copy, there is obtained an object reference

2) raiseSalary method is applied to the object reference, x and harry the same time get the Employee object references have salaries have increased twice

After 3) method, the parameter x is no longer used, the object harry continue to refer to that object

Achieved a state change object parameter method is complete

But the value is used to invoke Java objects, just as if we write a method two employees object exchange, if Java object uses call by reference, then you can achieve the results of the exchange of data exchange, but not actually, or a reference to the original variable like before this method call

Summarizes the use case method parameters of java:

1) a method can not modify a basic data types of the parameters

2) a method of an object can change state parameter

3) a method does not make reference to a new object parameter object

(8) configured Method

As already learned to write simple constructor to define the object initialization state, but because the object structure is very important, Java offers a variety of writing constructor mechanism

1. Overload

If multiple methods with the same name, different parameters, then generates a heavy load, the compiler must identify the specific implementation of a value type parameter type that method with a specific method to be compared with calls to select the appropriate method , can not find the corresponding parameters, it will produce a compilation error

Method signature: It should be noted method name and parameter types, return type is not part of the method signature, that can not have the same name, same parameter types but different return type of the value method

2. Default Domain initialization

If you do not explicitly assigned to the domain, it will be automatically set to the default value in the field: the value 0, Boolean flase, null object reference, but we'd better go initialize it, or will affect the readability (such as null we did not initialize it, to refer to it later, then it will error)

The main difference between fields and local variables: Local variables must explicitly to initialize it, or will be error

No argument constructor 3

If not programmed in the preparation of a builder class, then the system will automatically provides a no-argument constructor, this constructor all the fields set to the default instance, if the class provided at least one constructor, but does not provide free constructor argument, then no argument is not valid when the object is constructed, then it will error

4. The display field initialization

May be employed by the constructor overload class initialization state forms set class instance fields, ensuring in any case call the constructor, each instance field can be set to a meaningful value, this is a good design method, but we can also directly assign a value to any domain

private String name = " ";

Before performing the constructor, assignment operation performed first, when all of a class constructor wish to have the same value assigned to a particular instance of the domain, this method is particularly effective

The initial value is not necessarily constant value, you can call the method to initialize the domain

private int id = assignId();

private static int assignId(){

 

}

5. parameter name

One technique: parameter variables with the same name will be shielded instance fields. If the parameter name is named salary, then salary you will refer to this parameter, rather than the instance fields, but can be used in the form of this.salary to access instance fields, this represents an implicit parameter, which is constructed objects

public Employee( String name,double salary) {

this.name = name;

this.salary = salary;

}

6. constructor call another

Keyword this references the implicit method parameters, but that this has another meaning

If the first statement as the this type constructor (..) then the constructor will invoke another constructor

public Employee(double s) {

this("sss" + nextId,s);

nextId++;

}

Using this method very easy to use, so that the preparation of the common code portion configured only once to

7. initialization block

As already said two methods for initializing data fields 1) 2 is set in the constructor) assignment in a statement, in fact, there is a third mechanism of Java that is initialized block

In a class declaration may contain a plurality of code blocks, as long as the object class structure, these blocks will be executed

Such as

class Emoloyee{

private static int nextId;

{

id = nextId;

nextId++;

}

}

In this case, no matter which configuration is used to construct the object, id fields are initialized in the initial target block, run initialization block, before the operation of the body portion is configured, but this mechanism is usually not necessary, usually put them in the constructor

Here are the steps of the process calls the constructor:

1) All data fields are initialized to default values

2) the order of occurrence in a class declaration, all domains are sequentially executed initialization statements and initialization block

3) If the subject of the first line calls the second constructor constructor, then the implementation of the second constructor

4) the implementation of the theme of the constructor

If the code to initialize static class field is more complex, then you can use a static initialization block, the code into a block, and add a static

static{

Romdom generation = new Random();

nextId = generator.nextInt(100);

}

Static field will be initialized in the first class loading time, all static initializers and static initialization block will be executed in the order defined

Note: After Java7, Java program will first check there is not a main ()

8. A method of object destruction and finalize

Java garbage collector automatic, without manual recovery of memory, it does not support the Java destructor

Of course, if some objects using resources other than memory, so when the resource is no longer need to recycle and re-use is very important, we can add finalize any class () method, which will be the garbage collector call before clearing the object, in fact, do not rely on this method to recover a shortage of resources, because we do not know when this method will be used

If a resource need to be closed immediately after use, then you need to manually manage, run out after the object using the close () method to complete the appropriate cleanup

(9) bag

Java package to allow the use of the class organized, the standard Java class libraries distributed in multiple packages, all of the standard Java package in Java and Javax package hierarchy, the main reason for using the package is to ensure the uniqueness of the class names

The company proposed to use the Internet in the form of reverse domain name as the package name, and use different sub-packages in different projects

1. Import class

We are two ways to access another package of public classes

1) The first is to add the full package before the name of each class, as described below

java.time.LocalDate today = java.time.LocalDate.now (); // This is too much trouble

2) The second is to use the import statement

import statement is a reference to a concise description of classes included in the package, once using the import statement, using the class name does not need to write the entire packet

This statement is to import all the classes in the java.util package import java.util. *

Then can be used directly LocalDate today = LocalDate.now ();

You can also import a package specific class: import java.time.LocalDate;

Note: You can use an asterisk (*) to import a package, but you can not use import java * to import all packages with java prefix.

In most cases, simply import the required package, do not have to listen to them too much, but when naming conflict, can not fail to note the name of the package, such as java.util and java.sql package to date have class, If you use the import java.util. * import java.sql

Then it will use the Date class being given: Date date;

When the program can not determine which one to use, it is possible to add a specific import java.util.Date;

However, if two classes need to use, then you need to add the full package name in front of each class name

java.util.Date dedline = new java.util.Date();

java.sql.Date today = new java.sql.Date();

2. static imports

import statements can only import the class, you can also increase the import static methods and static function domains (but not recommended)

3. The class into the package

To the beginning of a class into the package, the package name must be placed in the source device, such as the following

package com.horstmans, corejava // it will be placed in a com / horstmans / corejava directory

public class Employee {

 

}

If the statement is not placed in the package, then the source file will be placed in a class default package (defaulf package)

The compiler does not check the directory structure of the source file at compile time, but if and when the package than with the directory, then the virtual machine can not find the class, and then can not run

4. Scope Package

As already contacting modifiers and private, public portion marking may be used any class, private tag portion may be defined only use their class, if no public and private, then this portion can be in the same package all access methods (in line 2 of the reason for the class, it is variable but do not meet, because before if certain classes in package java.awt; in the case, it will easily be mixed with other things this package, but now it jdk already made clear that users can not customize the start with Java packages)

You can use packet encapsulation to solve this problem

Design skills (10) class

1. must ensure that data private, and sometimes may need to write an accessor method or change the filter method, but still need to ensure that the best examples of private domain

2. the data must be initialized, java not initialize local variables, but would object to initialize instance fields, but it is best not to rely on the system default values, choosing instead to initialize all the display data can be specific provide a default value, or in the constructor to set defaults

3. Do not use too many basic types in a class, that class as an alternative to use other types of related basic use, this will make the class easier to understand and easy to modify

As an alternative to using the following examples Address field

private String street;

private String city;

private String state;

private int zip;

4. Not all fields need to access a separate domain and the domain change, such as once constructed given time to hire an employee, you can not modify it a go

5. too many responsibilities like decomposition, but do not go overboard, too much separation of class

6. class and method names can reflect their responsibilities

Name the class name is best to use a noun, an adjective in front of the noun they modify, for the method, the habit is accessor methods begin with a lowercase get, change control methods begin with set

7. Priority immutable classes

Immutable: there is no way to modify the state of the object, similar plugDays approach is not to change the subject, but returns a new object state has been modified

Change an object's problem is that if multiple views simultaneously multiple threads simultaneously update an object, it will happen concurrently modify the changes, the result can not be predicted, if the class is not made, then you can more safely thread shared objects.

 

Guess you like

Origin blog.csdn.net/weixin_41673515/article/details/90445835