All objects, all objects
1. abstract process:
1. All things are objects.
A specific thing like a dog or a house is an object, and an abstract concept like "service" is also an object.
You can use objects to store things. Dog objects can store dog heads and legs. "Service" objects can store service types, waiters, and customers.
You can ask the object to perform some operation. For example, let the dog scream and let the "service" object make a "home delivery" action.
2. The program is a collection of objects.
Each object in the program sends a message to tell each other what to do and cooperates to complete a task. For example, if you call a method of an object, the process of "calling" is "sending messages ".
3. An object can be composed of many other objects.
4. Each object has its own type.
For example, if A a = new A (); then the type of a is A, and the "class" is "type ". If you create a dog object, the type of the dog object is dog.
An important factor that separates classes from classes is: "What messages can be sent to them?" That is, each class has its own method.
5. A specific type of object can receive the same message.
A method is called to receive messages. Teddy and bomei all belong to dogs. The above sentence means that, because Teddy and bomei are both dogs, they can call the methods of dogs such as "call" and "run. For example:
BoMei and TaiDi inherit Dog, so the objects they create can call the Dog method.
This means that when writing BoMei or TaiDi-related code, we only need to write Dog-related code. This is one of the most powerful concepts in OOP. As follows:
I defined the legs attribute for Dog. In the test (Dog dog) method, the input parameter is "Dog", and the operation is also a property of the Dog class. However, when I call this method in line 16, the parameter I pass is the "BoMei" object. At this time, the operation is BoMei.
Similarly, when we want to operate on a TaiDi object, pass the TaiDi object to test. We don't have to define a test (TaiDi ta) and test (BoMei bo) method for TaiDi and BoMei respectively.
6. Each object is unique.
All objects have statuses, behaviors, identifiers, and types. For example, in the BoMei class above, "status" is "variable", "attribute", and the above BoMei class, and legs is its "status ". The behavior is "method" and "function", corresponding to bark () and eat () above. The behavior can change the State. For example, the test (Dog dog) above changes the legs attribute value. The type is the class to which the object belongs, and the "identifier" is equivalent to the same ID card, which is represented in java:Each object has a unique address in the memory.
2. Each object has an Interface
Apple has skin and kernel. It is sweet and grows on trees. Pear also has skin, also has nuclear, also sweet, also grows on the tree. Apple and pear have many similarities and are classified into the same type: fruit. This "Fruit" isABSTRACT Data Type(The so-called abstraction is to extract something similar to the appearance, such as skin, core, taste, and growth environment ).
ABSTRACT Data Types operate in the same way as basic data types. For example, you can use the following basic data types:
For abstract data types, you can use:
Create a variable of a certain type (create an object or instance) and call its method (send a message or request to let it know what to do ).
Each specific object has its own unique State. For example, the apple skin is red and the pear skin is green. Apple has less moisture and more pears. Therefore, Apple and pear are fruit, but they are independent individuals in the fruit category. These individuals are unique objects, so the relationship between objects and classes becomes clear:Each object belongs to a specific class that defines features and behaviors.The programming system treats abstract data types and general data types equally, and also performs type checks:
Both Apple and pear can eat, can squeeze juice, can make canned apple and so on. Eating, squeezing juice, and making canned food are behaviors (that is, methods, that is, requests). Apple and pears all satisfy these specific requests, so these specific requests are defined in the interface, the interface is also a type:
The interface only defines the request that can be sent to a specific object. What kind of request should I pay attention to when I peel, eat, or don't peel, and squeeze juice, this is all the details of a specific request. These detailed methods must be included in the Apple and pear subclasses, and these codes constitute an "Implementation ".
3. Each object provides services
Do not try to enclose all functions in one object. To complete a service project, you need to combine various objects. For example, to implement a printing module, we can define an object to check whether the configuration is normal, another object defines how to print a 4A drawing, defines an object set, calls the first two objects, and adds its own method to print the drawing.Every object can complete a task well, but does not try to do more.Then these objects work together to complete a service.
The above "concerted effort" is actuallyOne of the basic quality requirements of software design: High Cohesion.
Iv. Access Control
Java uses three keywords to control access to variables and methods:Public, private, and protected. Public can be accessed by other classes. private can only be accessed by internal methods of the class and the other classes are invisible. Protected indicates that only this class and its subclass are visible, and others are invisible. In addition, Java also hasDefault access permission: Package access permissionThe class can access other class members in the same package.
Cause 1: the client programmers (class callers) cannot touch what they should not. The caller only needs to call useful methods. Some variables are used by the designer to implement internal logic and do not need to be known to the client programmer. If the private variables are made public, they will not only interfere with the calling ideas of the client programmers, but may also be modified by the client programmers by misoperations.
Cause 2: the designer of the class library can change the internal working mode without affecting the calls of external client programmers.
5. combination, aggregation, and code reuse
Code reuse is one of the greatest advantages provided by object-oriented programming languages.
Directly Using a class to create an object is also reusable. The following 6th lines are reusing the Apple class.
Placing the object of a class in a new class (creating a member object) is also reusable:
In the above example, the Test class is synthesized using Fruit and Dog. Therefore, this concept is called composition ). If a combination occurs dynamically, it is called "aggregation )".
What is dynamic? See:
Line 1 does not create an Apple instance. Apple is instantiated only when line 11 is called. This is dynamic.
The combination is has-a, that is, cars have engines, companies have employees, Test has Fruit, and Dog.
Vi. Inheritance
Copy the existing class and add and modify the replica to create a new class. This is inheritance. When the source class (also called parent class, superclass, and base class) changes, the modified subclass also changes.
The above Circle inherits the Shape, and naturally inherits the color attribute of the Shape, as well as the getColor (), setColor (), and draw () methods. While inheriting, Circle modifies the draw () method to show that it is different from its parent class (this line is called override, that is, overwrite ). Of course, you can also add your own New Method to Circle.
If I modify the getColor method of the parent class:
Then this method of subclass changes.
The parent class contains the features and behaviors shared by all child classes. For example, in the preceding example, the color variable is shared (color is a feature), and the draw () method is also shared (draw () is a behavior ).
The parent class has the same type as the Child class.
From the code above, we can see that the Circle type is also the Shape type, which is easy to understand. bomei is a dog, Teddy is a dog, and Circle is a graph.
An important threshold for understanding object-oriented design is understanding:Type equivalence generated by inheritance.
There are two ways to make the parent class and subclass different:
1. Add a new method. (In this case, the relationship between the subclass and the parent class is: is like)
2. overwrite. (If we only overwrite and do not add a new method, the relation between the subclass and the parent class is: is ).
VII. Upward Transformation
In the above Code, the parameters in test () are the parent class Shape, and the draw () method of the parent class Shape is also called. When test is called in the main method, the Circle object of the subclass is passed in. the test method can also be called normally. In this case, the draw () method of the Circle is called.
It is often necessary to treat a subclass object as its parent type. The advantage of doing so is that it does not depend on the code of a specific type or be affected by adding a new type. For example, if you input a square subclass next time, the draw () method of the square is automatically called in test. If you add a new class: hexagonal, and then pass the hexagonal object to test, it can also be called normally.
The object-oriented design language uses "post-binding ". Only when the test () method is called can the specific type of the parameter be determined.
The process of using subclass as the parent type is called "upward transformation, upcasting ".
8,Container
We sometimes need to manage many objects. We don't know how many objects are needed, how long these objects can live, and how much space they need to be stored.
Containers (collections) help us solve the above problems. We put the object into the container and can expand it at any time.
Java has containers that meet various needs. For example: List (an ordered object Set), Map (an association between objects, also known as ing), Set (each object has only one and will not be repeated, similar to a Set in mathematics), of course, there are also queues (first put objects first come out, FIFO), trees (put many objects into the container in any order, when you have ranked each value in order) stack (the last object to be put first, and the LIFO Queue.
Object association, for example:
Associate "Zhang San" with "NAME" and "17" with "AGE". In this way, when obtaining "Zhang San", you only need:
1. Different containers have different functions (different interfaces and methods ).
For example, the following is the hierarchy of Stack and the interface method:
Below are the inheritance layers and methods of Queue:
The two are not under the same inheritance tree, and their respective methods have different functions. In fact, Stack is a type of post-import, first-out mode. You can only insert and delete Stack headers. A Queue is a first-in-first-out mode. It can only be inserted at the end of a Queue and deleted in the Queue header.
2. Different containers have different performance.
For example, ArrayList and rule list. For random access to an element, the time is fixed for the ArrayList, And the sorted list needs to start from the first element until the target element is found. If the target element is at the end of the container, it takes more time.
If an element is inserted, for ArrayList, all the elements after the inserted position must be moved one by one (think about the queue in real life). For the queue list, you only need to split the two objects at the insertion position and add the target elements to the object (think about the actual situation of friends hand in hand ). Is the insertion and deletion of the shortlist:
9,Generic, downward Transformation
In Java, all objects are inherited from objects, so we can see from the upward transformation rules that the containers that can store objects can store any Java objects.
In fact, what is placed in the container is not the object itself, but the object's "Reference", pointing to the object's address.
When you put a reference of a non-Object (such as String) into a container, because the container can only store Object references, it will be forcibly converted to Object references. Then, when you retrieve the reference again, it becomes the Object reference, not the String you want. As follows:
Although it is a reference of dog stored in the List and assigned to dog2, an error is reported because dog. get (0) obtains an Object-type reference. In this case, downward transformation is necessary.
The upward transformation is to use subclass as the parent class, while the downward transformation is to convert the parent type into a more specific type:
For example, the Object reference is forcibly converted to Dog.
The upward transformation is safe. For example, you can say that Apple is a fruit and a pear is a fruit. Therefore, you can forcibly convert any Object into an Object:
Downward transformation is not safe. You only know that it is a dog, but you do not know what it is:
In the above example, Teddy is put into the List. When the Object is retrieved, It is incorrectly converted to bomei, and the result is incorrect.
To avoid the above risks, Java introduces generics:
For example, it is clearly stated that only Teddy can be put in the List dog nest, then you will directly report an error if you put it in bomei.
For example, I already know that Teddy is sleeping in the List dog nest. If you call it bomei, an error is reported.
10,Object Lifecycle
Birth:
Every time you create an object, Java dynamically creates an object in a memory pool called "heap. Because it is dynamic, it is not until the runtime that you can know how many objects to create, what is the lifecycle of the object, and what is the specific type of the object. Move out the previous code to get a better understanding of "dynamic:
In the preceding example, the Apple instance is not created until test () is run.
Death:
Java's garbage collection mechanism will automatically discover when the object is no longer needed, and then destroy it to release the memory.
Java judges whether an object can be recycled. For example, if you create an object, an object is generated in the heap, and a reference (a number, point to the address of this object in the heap). The Garbage Collector has an early strategy. Every time a reference is generated, the counter will + 1. Every time a reference is reduced, the counter will be-1, when the counter is found to be 0, the object can be recycled. For example:
In step 4, per2 points to the address referenced by per1, so no reference is made to the object that points to age = 20. Therefore, the object will be recycled by the garbage collector.
11th,Exception Handling
An exception is an object. When a program encounters an error, it "throws" from the error point and is then "captured" by the dedicated processor corresponding to the error ". Therefore, if the code is normal, the Exception Code will not occur.
Some exceptions can be found only during running, mainly due to programmer errors. Such exceptions are called "RunTime exceptions", for example:
You know that test cannot be converted to an integer, but you still have to convert it. An error will be reported during running.
Another exception, called "non-runtime exception", should be prevented before running. For example, if you want to load a file from a certain path, you may not be able to find this file, so you must prevent it from happening before it can throw an exception:
You can also capture exceptions:
12,Concurrent Programming
To improve the response capability, we want to divide a task into multiple subtasks for independent operation and let them work together. These independent sub-tasks are "Threads", while "Working Together" is "concurrent ".
In fact, in a single processor environment, threads run in turn, and each thread time is allocated by the processor. On a multi-processor, there is a real "Working Together", that is, "Parallel ".
In the process of multi-thread concurrency to complete a job, resource sharing brings about hidden risks. For example, there is a chalk (Resource) on the table, and two children (threads) reach out to get chalk (resource preemption) at the same time ), then it will start. Therefore, a mechanism is required. When a child wants to take the chalk, he first protects the chalk (locks) and releases the lock when the child does not need it, another child can use chalk.
For more information, see: