[Java programming ideology-Study Notes] Chapter 1 Introduction to objects and programming ideology
1.1 abstract process
Java is an object-oriented language. One advantage of Java is that it only abstracts the problem to be solved, instead of worrying about the specific computer structure. This makes Java have perfect portability, that is, the Java slogan "Write Once, Run Anywhere ".
The so-called abstract process can be understood as modeling the problem to be solved. For example, if the problem to be solved is a person, we can model the person. The type is person, which has attributes such as name, gender, age, behavior, eating, and walking. Java can directly model and encode the code based on this, without considering the specific computer structure. So when we read the Java program, as the book says, "When you read the code that describes the solution, you are also reading the Problem description ".
1.2 attributes of an object
As we have observed, people have attribute names and ages, circles have attribute radius, triangles have attribute edges and angles, and each object has certain attributes, it can also be called an attribute as a member of an object.
1.3 each object provides services.
Providing services for every object is also an important idea of object-oriented.
Just like in the human world, house building is for accommodation, car building is for travel, school building is for education, and hospital building is for medical treatment. Similarly, the object creation in Java is certainly intended for users. If the created object is useless and cannot provide any useful services, it becomes a garbage object.
Since each object can provide services, it means that the object can do some things. Some common methods can be used by other objects, which are also called interfaces.
1.4 each object has an Interface
Object-oriented has one of the most important ideas-collection of things from their classes. Everything is regarded as an instantiated object, and any instantiated object must be created according to a template. This template is a class. If you have read a creature, you should understand that any creature can be classified based on the field, gate, outline, object, family, genus, and species. If it is not a creature, for example, viruses, stones, sand, etc. But when we call their names, we also find their classes.
Definition of a popular interface: In simple terms, an interface refers to "What can I do ". (Open the java api and check the java. lang package. The interfaces in it are as follows:Appendable,Cloneable,RunnableAnd the suffix is "-able". Such a name also reflects the meaning of the interface)
The question is, why is the interface used? Why does each object have an interface? Let's take a look at the TV's instantiated object. When we press the OPEN button, it will receive a "open" request, and then it will do some internal work, and the screen will be lit up, when we press the next channel, it receives the request for "next channel", then it does some internal work, and finally displays the next channel. In fact, each object should have the same working mechanism. For example, if a person eats a meal or a person eats a meal, the system will receive a "eat" request, and then it will be a series of digested work, at last, it turns into the energy required for each cell to work. We abstract this kind of working mechanism, so we have the concept of interfaces and implementations. Interface, just like a button that is exposed to the outside of the TV, with function buttons such as opening, going up/down, Volume +, just like hiding complex internal work in a TV, it is better to hide it. Every object has an interface to avoid designing the class into a black box. If there is no interface on the TV, the remote control cannot be used, what is the use of such a TV set? Therefore, every programmer is warned that at least one public method must be defined for the design class.
1.5 specific implementation of hiding
Why do we need to hide the specific implementation? In addition to the reason described in section 1.4, there is another important reason. You need to know that there are two types of programmers in the programming world: Class creators (those who create new data types ), the two are called client programmers (class consumers who use data types in their applications ). The most common assumption is that the creator of the Java class library is A1 (that is, the class creator), and the programmer who uses the Java class library is A2 (that is, the client programmer ). A1 and A2 form a relationship. A1 is responsible for constructing classes, while A2 uses the classes provided by A1 for development. Assume that the class creator develops a class to calculate the number of combinations.CombinationIn mathematics, the formula for the number of groups is C (n, m) = m! /N! (M-n )!, We can define two methods. One is to calculate the factorial, and the other is to calculate the number of combinations. We do not want the method to calculate the factorial to be exposed as an interface, because once exposed, the client programmer can set parameters and modify internal implementations at will. Therefore, such specific implementations should be hidden to avoid destruction and reduce program bugs, this is also a service for client programmers, because they will know which methods are available and which methods are unavailable. Another reason is that, when I need to modify the hidden implementation, it will not affect the client programmers. For example, I used to use loops to implement factorial calculation, but later I found it better to use recursion, even the method name has been changed, but the interface of this class has not changed, so it does not affect the client programmer.
In fact, we must not only hide specific implementations, but also hide the attributes of objects. The hiding of these attributes and specific implementations is called encapsulation in object-oriented systems. Encapsulation means protection. For example, if a person has an attribute of age, we all know that age must be non-negative. If it is not encapsulated, some naughty programmers can tamper with it at will, for example, if the age is changed to-1, how can it be a negative number? Therefore, encapsulation is introduced to prevent tampering and protect object attributes.
1.6 reuse implementation
The specific implementation of reuse is a major feature of Java. The relationships between classes are involved: aggregation, combination, inheritance, association, and dependency.
In short, aggregation is a relationship of ownership, but the life cycles of the two are inconsistent. For example, if a person owns a computer, it is an aggregation relationship. The life of a computer has reached, but the life of a person has not reached, man's life has arrived, but the computer's life has not yet arrived;
A combination also has a relationship, but also a strong aggregation relationship. The lifecycles of the two are the same. For example, no one can leave people and their own brains;
Needless to say about inheritance. For example, Apple inherits from fruit and apple is fruit;
Association also has a relationship. The difference is that association is a one-to-many relationship. For example, one order can only have one customer, and one customer can have multiple orders;
Dependency is the use of relationships. For example, if a person wants to cross the river, he needs to use a ship. In the code, a class method defines the local variables of the dependent class, or the dependent class is used as a parameter for this method.
1.7 inheritance
Inheritance is a way to reuse code. It refers to creating a new class based on an existing class. The inherited class is called a base class (or parent class or superclass ), the inherited class becomes the export class (or subclass or secondary class ).
There are three types of inheritance: 1. the export class does not do anything, so the export class is exactly the same as the base class; 2. the export class overwrites (modifies) the method of the base class, that is, the export class replaces the base class. 3. the export class adds new methods and may overwrite the methods of the base class. At this time, the export class extends the base class. In fact, we usually extend the base class during inheritance.
In terms of inheritance, the biggest difference between Java and C ++ is that each class inherits only one class. In addition, all classes in Java inherit directly or indirectly from the root class.Object, As shown in
1.8 interchangeable objects accompanied by Polymorphism
As shown in section 1.7, we can say that a right triangle is a triangle and an equi-edge triangle is a triangle, but not necessarily a right triangle or an equi-edge triangle. Suppose we have already designed the triangle inheritance system, and then we design another class that operates the triangle. There is a method in the class to fill the triangle, but three triangles are known, that is, right triangle, waist triangle and equi triangle. Do you want to fill these three triangles with heavy load? No. polymorphism allows us to accept the generalized type of triangle on the parameter. That is to say, no matter which triangle is used, it is regarded as a triangle on the polymorphism. Therefore, it can be accepted by the parameters of the method, therefore, it can also be filled. For example, the following program:
// Do not use polymorphism void fill (e) {print ("");} void fill (e) {print (" ");} void fill (equi e) {print ("filled equi triangle");} // use the polymorphism void fill (triangle e) {print ("filled" + e );}
It can be seen that the code is more concise due to polymorphism.
At this point, I would like to add a question: encapsulation, inheritance, and polymorphism are three characteristics of object-oriented.
1.9 single inheritance Structure
As shown in section 1.7, all classes in Java ultimately inherit from a single base class, that isObject. Such a single inheritance structure has three advantages:
1.10 containers
We all know that the size of an array must be specified when it is declared, and the size cannot be changed once it is specified. The problem arises. What if the size of the array is still insufficient? You can only redefine an array, which is inconvenient. To solve this problem, Java provides a container that dynamically adjusts the container size based on the number of elements required by the container. Container hasSet,Map,ListAnd stacks, queues, trees, etc.ArrayList.
1.11 creation and lifecycle of Objects
In Java, you only need to useNewThen the object is created in the heap. if the object is created on the stack, the compiler can determine its lifecycle and destroy it, however, if the object exists in the heap, the compiler cannot determine the survival time of the object. In order to destroy objects and release memory, Java provides a garbage collection mechanism, so programmers no longer need to manually destroy objects, which makes programming much easier.
Of course, this is also a disadvantage in Java, because the object exists in the heap, so the creation and operation of the object will be slower, and the destruction of the object will be handed over to the garbage collector, this is a bit uneasy. If the program exits, but the Garbage Collector has not destroyed the object, the Java program occupies a high memory and is world famous.
1.12 Exception Handling: handling errors
For example, we design a simple division method.Divide
int divide(int x, int y) { return x / y; }
At this time, if the value of y is 0, the program runs abnormally, and then quit without saying anything, it is obvious that the program experience is too bad, in fact, this situation is not too bad, it would be dangerous to design programs for banks, military, and aviation, but not handle exceptions. To ensure program robustness, you must be able to handle exceptions.
1.13 concurrent programming
Many programming problems require that the program can stop the work being done and solve other problems. Some programs also require the ability to do multiple things at the same time. For example, we want to download multiple resources at the same time. resumable download is supported and the download can be paused. For example, if QQ is online, you can view the status of friends while chatting. You can only use multiple threads to solve these problems.