Java Core Technology - Objects and Classes

1 An overview of object-oriented programming

Object-oriented programs are composed of objects, each of which contains specific functional parts exposed to the user and hidden implementation parts.

1.1 Class

A class is a template or blueprint for constructing an object, and the process of constructing an object from a class is called creating an instance of the class.

Package: 

Formally, it is an implementation that combines data and behavior in one package and hides the data from the user of the object.

The data in the object is called the instance domain , and the process of manipulating the data is called the method.

For each specific class instance (object) there is a specific set of instance field values, and the set of these values ​​is the current state of the object.

The key to implementing encapsulation is that methods in a class must not directly access the instance fields of other classes, and programs can only interact with object data through object methods.

In Java, all classes originate from a "magical superclass", which is Object.

The process of extending one class to build another class is called inheritance.

1.2 Objects

Three main properties of objects:

The behavior of the object - what operations can be applied to the object, or what methods can be applied to the object.

The state of the object - how the object responds when those methods are applied.

Object identification - how to identify different objects with the same behavior and state.

1.3 Identifying classes

A simple rule for identifying classes is to look for nouns in the process of analyzing a problem, and methods correspond to verbs.

1.4 Relationship between classes

Among classes, the most common relationships are

*Dependency ("uses-a"): A class's methods manipulate objects of another class, we say a class depends on another class. Reducing dependencies reduces coupling.

* Aggregate("has-a"): Objects of class A contain objects of class B.

*Inheritance ("is-a"): used to express special and general relationships.


 

2 Use predefined classes

2.1 Objects and Object Variables

To use an object, you must first construct the object and specify its initial state . A constructor is a special method used to construct and initialize objects.

The name of the constructor should be the same as the class name.

Understand the difference between objects and object variables.

It is important to realize that an object does not actually contain an object, but only refers to an object. The value of any object variable is a reference to an object stored elsewhere.

Local variables are not automatically initialized to null, but must be initialized by calling new or setting them to null.

2.2 LocalDate class

In Java, the Date class is used to represent points in time, and the LocalDate class is used to represent the calendar notation.

Instead of using the constructor to construct the LocalDate class, use a static factory method to call the constructor on your behalf: LocalDate.now() will construct a date object representing the date when the object was constructed.

2.3 mutator methods and accessor methods

Similar to the toUpperCase method of the String class, when this method is called, the original object remains unchanged, and a new object that capitalizes all characters in the original object is returned.

In contrast, those methods that change the state of the original object are called mutator methods. (GregorianCalendar.add)

Accessor method: A method that only accesses the object without modifying it.


 

3. User-defined class

Instance field (private) + instance method

3.1 Constructors

* Constructor has the same name as the class

*Each class can have more than one constructor

* Constructor can have 0, 1 or more parameters

* Constructor has no return value

* Constructor is always called with new operation

3.2 Implicit and explicit parameters

A general method has two parameters. The first parameter is called an implicit parameter, which is the class object that appears before the method name. The second display parameter is the numeric value in parentheses after the method name.

In each method, the keyword this represents an implicit parameter.

3.3 Advantages of packaging

* a private data field

* a public domain accessor method

* a public domain mutator method

Be careful not to write accessor methods that return a reference to a mutable object, if you need to return a reference to a mutable object, you should clone it first.

public Date getHireDay(){

  return (Date)hireDay.clone();

}

3.4 Class-based access rights

A method can access private field data of all objects of its owning class.

3.5 final instance field

The final modifier is mostly applied to fields of primitive types, or fields of immutable classes.
For mutable classes, the final keyword only means that the object reference stored in the mutable class object will no longer point to other class objects, but the object can still be changed. (StringBuilder)


 

4 Static fields and static methods

4.1 Static domain (class domain)

If a field is defined as static, there is only one such field per class. Static fields exist even if none of the class objects exist. It belongs to the class, not to any independent object.

4.2 Static constants

Math.PI、System.out

Public constants can only be accessed and cannot be modified: public final

The system class has a setOut method, which can set System.out (final variable) to a different stream, because the setOut method is a local method and is not implemented in the Java language, which can bypass the access control mechanism of the Java language.

4.3 Static methods

A static method is a method that cannot perform operations on an object.

A static method cannot access the instance field of the class, but can access the static field of its own class.

Two cases of using static methods:

* A method does not need to access the object state, its required parameters are provided by explicit parameters (Math.pow)

* A method only needs to access the static field of the class

4.4 Factory Methods

There is another common use of static methods: static factory methods - methods that do not pass  new, but use a static method to provide their own instance to the outside world

The main difference between static factory-constructed objects and constructor-constructed objects (more flexible):

1. You can name the constructor

2. No need to create a new object every time it is called

3. Can return a subclass of the original return type


 

5 Method parameters

There are two ways of passing parameters to methods: call-by-value and call-by-reference.

A method can modify the variable value corresponding to the pass-by-reference, but cannot modify the variable value corresponding to the pass-by-value call.

Java uses call by value.

There are two types of method parameters:

*Basic data types

*Object reference

Usage of method parameters in Java:

* A method cannot modify a parameter of a primitive data type

* A method can change the state of an object parameter

* A method cannot have the object parameter refer to a new object


 

6 Object Construction

6.1 Overloading

Overload resolution is done by the compiler.

Method signature: To fully describe a method, you need to indicate the method name and parameter types. (the return type is not part of the method signature)

6.2 Default Domain Initialization

If a field is not explicitly given an initial value in the constructor, it is automatically assigned the default value: 0 for numeric values, false for booleans, and null for object references.

This is the main difference between fields and local variables - local variables do not have default initialization, local variables must be explicitly initialized.

6.3 No-argument constructors

If the class provides at least one constructor, but no parameterless constructor, it is considered illegal to construct an object without providing parameters.

The system provides a default constructor only if the class does not provide any constructors.

6.4 Calling another constructor

If the first statement of a constructor is of the form this(), the constructor will call another constructor of the same class.

6.5 Initialization block

The method of initializing the data field:

1. Set the value in the constructor

2. Assignment in declaration

3. Initialization block

Steps to call constructor initialization:

All data fields are initialized to default values ​​(static field initialization) -> data field initialization statement -> initialization block -> constructor

6.6 Object destructors and finalize methods

The finalize method will be called before the object is cleaned up by the garbage collector.

If a resource needs to be closed immediately after use, a close method can be applied to complete the corresponding cleanup operation.


 

7 pack

The main reason to use packages is to ensure uniqueness of class names.

7.1 Importing classes

A class can use all classes in its own package, as well as public classes in other packages.

Only one package can be imported using an asterisk (*), not all packages prefixed with java using import java.* or import java.*.*.

The reference problem of common classes in two packages can be solved by adding a specific package name.

If two classes of the same name in two packages are to be referenced, the full package name can be prefixed to each class name.

7.2 Static import

The import statement can not only import classes, but also adds the function of importing static methods and static fields.

7.3 Putting classes into packages

The compiler operates on files (files with file separator and extension .java). while the Java interpreter loads classes (with . delimiters)

7.4 Package scope

Sections marked public can be used by any class; sections marked private can only be used by the class in which they are defined. If no public or private is specified, this part (class, method, variable) can be accessed by all methods in the same package.


 

8 Design Tips

1. Be sure to keep your data private

2. Be sure to initialize the data

3. Don’t use too many primitive types in your classes

4. Not all domains require separate domain accessors and domain mutators

5. Break down classes with too many responsibilities

6. Class and method names should reflect their responsibilities

7. Prefer immutable classes (consider the case)

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325178363&siteId=291194637