All things are objects

Source: Internet
Author: User
Tags getcolor pears

First, the abstract process:


1, all things are objects.

The concrete object of the dog and the house is the abstract concept of "service" as well as the object.

You can use objects to store things. Dog objects can store dog head, dog legs and so on. The service object can store service types, waiters, customers, and so on.

You can require an object to perform some action. For example, let the dog cry, let the "service" object to do a "door-to-gate" action.

2, program is a collection of objects

Each object in the program can work together to accomplish a task by sending a message telling each other what to do. For example, if you call a method of an object, the "call" process is "send a message".

3, an object can consist of many other objects.

4, each object has its own type.

For example, a a=new a (); So, the type of a is a, "class" is "type". You create a dog object, so the type of dog object is the dog.

One important factor that distinguishes a class from a class is "what message can be sent to it", that is: each class has its own method.

5, a specific type of object can receive the same message.

The method is called when the message is received. Teddy and Bo are all dog-like. The above phrase means: Because Teddy and Bo are both dogs, so they can call the dog's "call", "run" and other methods. Like what:

Bomei and Taidi inherit the dog, so the objects they create can call the dog's method.

This means that when we are writing Bomei or Taidi-related code, we just need to write the dog-related code, which is one of the most powerful concepts in OOP (object-oriented design). As follows:

I defined the legs attribute for dog. In the test (dog) method, the parameter I passed in was "dog", and the property of the dog class was manipulated. But when I call this method in line 16, I pass the parameter "Bomei" object, at this time, the operation is Bomei.

Similarly, when we are working with a Taidi object, we pass the Taidi object to test. We don't have to define a test (Taidi ta), test (Bomei bo) method separately for Taidi and Bomei.

6, each object is unique

Objects have states, behaviors, identities, and types. For example, the Bomei class above, "state" is "variable", is "attribute", above the Bomei class, legs is its "state". Behavior is "method", "function", corresponding to the above bark (), eat () and so on. Behavior can change the state, such as the above test (dog) changes the value of the legs property. The type is the class to which the object belongs, and "identity" is equivalent to an identity card, which behaves in Java as: Each object has a unique address in memory.

Two, each object has an interface

Apples are skin, have nuclei, are sweet and grow on trees. Pears also have skin, also have the nucleus, also is sweet, also grows in the tree. So the apples and pears have a lot of similarities and are divided into the same type: Fruit class. This "fruit" is an abstract data type (the so-called abstraction, which extracts something similar, such as skin, nucleus, taste, growing environment, etc.).

Abstract data types operate in a way that is consistent with basic data types. For example, for basic data types, this can be used:

For abstract data types, you can use this:

Create a variable of a type (create an object or an 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, pear skin is green. Apple has less water and more pear water. Therefore, apples and pears are fruits, but they are separate individuals in the fruit category, these individuals are the only object, then the relationship between the object and the class is clear: Each object is a specific class that defines the attributes and behavior. the programming system treats abstract data types in an equal manner to the general data types, and also for type checking, and so on:

Apples and pears can eat, can squeeze juice, can make canned apples and so on. Eat, squeeze juice, make cans This belongs to the Act (i.e., the method, that is, the request), and both apples and pears satisfy these specific requests, and the specific requests are defined in the interface, and the interface is a type:

Interface just defines the request can be made to a particular object, then specific to the apple, pear what kind of request, skinning or not peeling, squeeze juice to pay attention to what, this is the specific request of the details, in the Apple class, pear class must have these specific details, the code constitutes an "implementation."

Three, each object to provide services

Do not try to put all the functions are crowded in an object, to complete a service project requires the coordination of various objects, such as implementing a print module, we can define an object specifically to check whether the configuration is normal, another object defines how to print a 4A drawing, and then define a collection of objects, call the first two objects, In addition to their own methods to finally print out the drawings. Each object can do a good job, but it doesn't try to do more. These objects then work together to complete a service.

The above "concerted effort" is actually one 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, protected. Public other classes can be accessed, private only in this class and the internal methods of the class can be accessed, other classes are not visible. Protected indicates that only subclasses of this class and inheriting this class are visible, others are not visible. In addition, Java has a default access rights: Package access , classes can access other class members in the same package.

Reason for access control 1: Let the client programmer (the caller of the class) not touch the part that they should not touch. Callers only need to invoke useful methods, and some variables are used by designers to implement internal logic and do not need to be known by the client programmer. If the private variables are made public, they can interfere with the client programmer's idea of invocation, and may be modified by the client programmer to modify the state value.

Reason for access Control 2: Designers of class libraries can change the way they work internally without affecting the calls of external client programmers.

V. Combination, aggregation, code reuse

Code reuse is one of the greatest advantages offered by object-oriented programming languages.

Creating an object directly from a class is also a reuse, and the 6th line below is reusing the Apple class.

Placing an object of a class in a new class (creating a member object) is also a reuse:

In the example above, the test class was synthesized with fruit and dog, so this concept is called: Combinatorial (composition). If the combination occurs dynamically, it is called an aggregation (aggregation).

What is dynamic happening? See:

Line 7th does not create an Apple instance, and when 11 lines are called, the apple is instantiated, which is what happens dynamically.

The combination of the relationship is: Has-a, that is: The car owns the engine, the company has employees, test has fruit, Dog.

Vi. Succession

Copy the existing class, and then add and modify the replica to create a new class, which is inheritance. When the source class (also called: parent, superclass, base class) changes, these changes also occur for the modified subclass.

The above circle inherits shape and naturally inherits the color property of shape, as well as the GetColor (), SetColor () method, Draw () method. While inheriting, Circle modifies the draw () method to show that it is different from the parent class (this behavior is called override, which is: overwrite). Of course, circle can also add its own new method.

If I change the GetColor method of the parent class:

Then this method of the subclass has changed.

The parent class contains the attributes and behaviors that are shared by all child classes. For example, the color variable is shared (color is an attribute), and the Draw () method is also shared (Draw () belongs to the behavior).

The parent class has the same type as the child class.

As can be seen from the above code, the circle type is also the shape type, this is easy to understand, Bo Mei is a dog, Teddy is a dog, the circle is graphics, no problem.

The important threshold for understanding object-oriented design is understanding: the type equivalence generated by inheritance .

Two ways to make the parent class differ from the child class:

1. Add a new method. (At this point, the child class has a relationship with the parent class: is a)

2, overlay. (The child class has a relationship with the parent class if it is only overwritten without adding a new method: is a).

Seven, upward transformation

In the above code, the parameter in test () is the parent shape, and the call is also the draw () method of the parent shape. When test is called in the Main method, the subclass Circle object is passed in, and the test method can be called normally, and then the draw () method of Circle is called.

It is often necessary to treat a subclass object as its parent type, which has the advantage of not relying on a particular type of code and not being affected by the addition of a new type. For example, the next time you pass in a square subclass, Test automatically calls the square's draw () method. If you add a new class: Hex, and then pass the hexagonal object to test, it can also be called normally.

The object-oriented design language uses "late binding." The specific type of the parameter can be determined when the test () method is called specifically.

The process referred to as the parent type is called "upward transformation, upcasting".

Eight , Container

We sometimes need to manage a lot of objects, we don't know how many objects we need, we don't know how long these objects can live, we don't know how much space to store these objects, ask Sanbuzhi.

The container (collection) helps us solve the above problem. We put the object in the container and can expand it at any time.

There are containers in Java that meet a variety of needs. For example: List (an ordered set of objects), map (the association between objects, also known as mappings), set (each object has only one, does not repeat, similar to the set of mathematics), of course, there are queues (first put in the object first out, FIFO), the tree (in any order to put many objects into the container, Each value is sequenced when you traverse it, the stack (the last object put in first, the LIFO queue), and so on.

The Association of objects such as:

Associate "Zhang San" with "NAME", associating "17" with "age", so that when acquiring "Zhang San", only the following is required:


1, different containers have different functions (different interfaces, different methods).

For example: The following is the stack's inheritance hierarchy and interface methods:

Here is the hierarchy and method of inheritance for the queue:

They are not under an inheritance tree, and their methods do not function the same. In fact, a stack is a last-in-first-out pattern that can only be inserted and deleted on the stack header. A queue is a first-in, out-of-state pattern that can only be inserted at the end of a team and deleted at the team header.

2, different container performance is different

For example: ArrayList and LinkedList. If you are randomly accessing an element, the time is fixed for ArrayList, and LinkedList needs to find it from the first element until the target element is found, and if the target element is at the end of the container, it will take more time.

If you insert an element, for ArrayList, the element behind the insertion position is moved back one (think of the cut in the actual life), and for LinkedList, only the two objects in the insertion position should be disassembled. Then add the target element (think about the actual life of the children in hand-holding situation). is the insertion and deletion of LinkedList:


Nine , generics, down-conversion

In Java, all objects inherit from object, so the law of upward transformation shows that the container that can hold object can hold any Java object.

In fact, the container is not placed in the object itself, but only the object's "reference", pointing to the address of the object.

When you put a reference to a non-object object (such as a string) into a container, because the container can hold only the object reference, it will be forced to be converted to an object reference. Then when you remove the reference again, it becomes an object reference, not the string you want. As follows:

Although the reference to the dog is stored in the list, and it is assigned to DOG2, it is an error because Dog.get (0) takes a reference to the object type. At this point, it is necessary to use downward transformation.

The upward transformation is used as the parent class, and the downward transformation is to convert the parent type to a more specific type:

For example, cast the object reference to dog.

The upward transformation is safe, for example, you can boldly say: Apples are fruits, pears are fruits, so you can boldly force any object to be converted to object:

Downward transformation is not safe, you only know it is a dog, but you do not know what kind of it is:

The example above puts Teddy in the list, takes out the object, but mistakenly converts it to Chengbome, resulting in an error.

To avoid these risks, generics are introduced in Java:

For example, make it clear that the list in the kennel can only put Teddy, then you put the BO will be directly error.

For example, I already know that the list in the kennel sleep is Teddy, you take out to shout it Chengbome, then also will error.

10 , the life cycle of an object

Was born:

Every time you new an object, Java dynamically creates an object in a pool of memory called the heap. Because it is dynamic, it is not until the runtime knows how many objects to create, what the object's life cycle is, and what the object's specific type is. Then move out of the previous section of code to deepen your understanding of "dynamics":

In the example above, Apple instances are not created until test () is run.

Death:

Java's garbage collection mechanism automatically discovers when an object is not used, and then destroys it to achieve the purpose of freeing up memory.

Java is a complex thing to judge whether an object can be recycled. For example, in general, an object is created, an object is generated in the heap, and a reference to the object is placed in the stack (a number that points to the address of the object in the heap), and the garbage collector has an early strategy, with each reference being generated, the counter is +1, and every time a reference is reduced, the counter is 1, When the counter is found to be 0 o'clock, it indicates that the object can be recycled. Such as:


In the fourth step, Per2 points to the address referenced by Per1, so there is no reference to the object that points to age=20, so that object is reclaimed by the garbage collector.

11 , Exception Handling

An exception is an object that, when an error occurs, "throws" it from that error point and is then "caught" by the specialized processor that the error corresponds to. Therefore, if the code is normal, the exception code will not occur.

Some exceptions are found at run time, mainly due to the programmer's mistakes, which are called "Runtime exceptions", such as:

You know that test can't be turned into an integer, and you have to turn it, and the runtime will get an error.

There is also an exception, called "Non-runtime exception", that is, before the run to prevent, such as want to load a file from a path, in this case, there is no possibility of finding this file, then you have to make a precaution, you can throw an exception:

You can also catch exceptions:


12. Concurrent Programming

In order to improve responsiveness, we want to separate a task into multiple sub-tasks to run independently and let them work together. These standalone subtasks are "threads", while "working together" is "concurrency".

In fact, in a single processor environment, threads are run by turns, which are divided by the processor to the time of each thread. The real "work together", or "parallel", exists on multiple processors.


Multi-threaded concurrent completion of a work process, resource sharing is a hidden danger, such as a table with a piece of chalk (resources), two children (threads) at the same time reach for the chalk (to seize resources), then will fight up. Therefore, there will be a mechanism, when a child to go to fetch chalk, the first to protect the chalk (locking), and so the children do not have to release the lock, another child can use chalk.

For more information, please follow:

All things are objects

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.