Java Object-Oriented Programming

Source: Internet
Author: User
Java Object-Oriented Programming-general Linux technology-Linux programming and kernel information. The following is a detailed description. The core of Java is object-oriented programming. In fact, all Java programs are object-oriented and you have no choice. This is different from C ++ because you can choose whether to enable object-oriented programming. Object-Oriented Programming is inseparable from Java. Therefore, you must understand its basic principles before writing the simplest Java program. Therefore, this chapter begins with the concept of object-oriented programming.
1. Two Models
We know that all computer programs are composed of two types of elements: code and data. In addition, in terms of concept, a program can also be organized and written based on its code or data. That is to say, some programs are written around "what is happening", while others are written around "who will be affected. These two types determine the construction method of the program. The first method is called the process-oriented model. All programs written with it have the characteristics of linear execution. A process-oriented model can be considered as a model in which Code acts on data. A Procedural language like C uses this model quite successfully. However, as mentioned in chapter 1st, problems may occur when programs become larger and more complex.
To manage the increasing complexity, the second approach, object-oriented programming, was conceived. Object-Oriented Programming organizes programs around its data (that is, objects) and strictly defined interfaces for this data. Object-oriented Programs use data to control code access. As you can see below, converting the controlled entity into data can benefit the program from several aspects in its organizational structure.
2 Abstraction
An essential element of object-oriented programming is abstraction. Abstract actions are used to process complexity. For example, people don't think of a car as a set of devices composed of tens of thousands of independent parts, but think of it as an object with its own unique behavior. This abstraction makes it easy for people to drive a car to a grocery without being overwhelmed by the complexity of making up all parts of the car. They can ignore the details of the engine, drive, and brake systems and take advantage of the car as a whole.
Hierarchical classification is an effective way to manage abstraction. It allows you to physically break complex systems into more small pieces that are easier to process. In terms of appearance, a car is an independent object. Once you get inside, you will see that a car consists of several subsystems: driving system, braking system, audio system, safety belt, heating, portable phone, etc. Further subdivided, these subsystems are composed of more specialized components. For example, the audio system consists of a radio, a CD player, and perhaps a tape amplifier. An important inspiration from this is that you manage complex cars (or any other complex system) through hierarchical abstraction.
Hierarchical abstraction of complex systems can also be used in computer programming. The data of the traditional process-oriented program can be abstracted and expressed by several component objects. The process steps in the program can be viewed as collecting messages between these objects. In this way, each object has its own unique behavioral characteristics. You can treat these objects as specific entities so that they can respond to messages that tell them what to do. This is the essence of object-oriented programming.
Object-oriented concepts are the core of Java. For programmers, it is important to understand how these concepts are converted into programs. You will find that in any major software engineering project, software inevitably needs to go through a lifecycle like concept proposal, growth, and aging, and object-oriented programming, it can make the software in every stage of the life cycle not surprising, have enough ability to respond. For example, once you have defined objects and concise and reliable interfaces pointing to these objects, you can easily and confidently remove or replace certain components of the old system.
3. Three Principles of Object-Oriented Programming
All Object-Oriented Programming Languages provide mechanisms to help you implement object-oriented models. These mechanisms are encapsulation, inheritance, and polymorphism. Now let's take a look at their concepts.
Encapsulation
Encapsulation is a programming mechanism that binds code and the data it processes together. This mechanism ensures that programs and data are not subject to external interference and are not misused. One way to understand encapsulation is to think of it as a black box, which can prevent external defined code from freely accessing internal code and data. Access to code and data in the Black Box is strictly controlled through an appropriate defined interface. If you want to compare it with something in real life, you can consider automatic transmission on the car. Automatic Transmission contains hundreds of bits of information about the engine, such as the acceleration you are heading for, the slope of your road surface, and the current gear. As a user, there is only one method that affects this complex encapsulation: shift lever. For example, you cannot influence the drive by using a turn signal or a windshield wipe. So the shift lever is the only interface connecting you to the drive. In addition, any operation in the drive object will not affect the external object. For example, the drive device will not turn on the headlights! Because automatic transmission is encapsulated, any car manufacturer can choose a suitable method to implement it. However, from the driver's point of view, they have the same purpose. The same idea can be used for programming. The advantage of code encapsulation is that everyone knows how to access it, but you don't have to consider its internal implementation details, or be afraid that improper use will bring negative effects.
The basic unit of Java encapsulation is class. Although the class will be detailed in later sections. It is still necessary to briefly discuss it. A class defines the structure and behavior (data and code) that will be shared by an object set ). Each object of a given class contains the behavior and structure defined by this class, as if they were cast from the same class model. For this reason, objects are sometimes considered as instances of a class ). Therefore, a class is a logical structure, and an object is a real physical entity.
When creating a class, you must specify the code and data that constitute the class. In general, these elements are called members of the class ). Specifically, data defined by a class is called a member variable or an instance variable ). The code used to operate data is referred to as the member method (member methods) or the method (methods ). If you are familiar with C/C ++, you can understand it as follows: The method called by Java programmers is the function called by C/C ++ programmers ). In programs fully written in Java, the method defines how to use member variables. This means that the behavior and interface of a class are defined through methods, which operate on its instance data.
Since the purpose of a class is to encapsulate complexity, there should be a hidden implementation complexity mechanism inside the class. Every method or variable in the class can be marked as private or public ). The public interface of the class represents everything that external users of the class need to know or can know. Private methods and data can only be accessed by the member code of the class, other code that is not a member of a class cannot access private methods or variables. Since private members of a class can only be accessed by other parts of the program through the public methods of the class, you can ensure that things that do not want to happen will not happen. Of course, the public interface should be carefully designed to avoid exposing the internal content of the class too much (see-1 ).

-1 encapsulation: public methods used to protect private data
Inheritance
Inheritance is the process in which an object obtains the attributes of another object. Inheritance is important because it supports the concept of layer-by-layer Classification. As mentioned above, most knowledge can be managed hierarchically (from top to bottom. For example, a distinguished hound is part of a dog, a dog is part of a mammal, and a mammal is part of an animal. Without the hierarchical concept, we have to define all attributes of each animal separately. With inheritance, an object only needs to define unique attributes in its class, because it can inherit all common attributes from its parent class. Therefore, it can be said that the inheritance mechanism makes it possible for an object to become a specific instance of a more general class. Let's discuss this process in more detail.
Most people think that the world is composed of objects, and objects are connected by hierarchical structures such as animals, mammals, and dogs. If you want to describe animals in an abstract way, you can describe them by attributes such as the size, intelligence, and type of the backbone system. Animals also have definite behaviors. They also need to eat, breathe, and go to bed. This description of attributes and behaviors is the definition of animals.
If you want to describe a more specific animal type, such as a mammal, they will have more specific attributes, such as the tooth type, breast type, and so on. We say that mammals are sub-classes of animals, while animals are superclasses of mammals ).

Because mammals are animals that require more precise definitions, they can inherit all attributes from the animals. A subclass of deep inheritance inherits all the attributes of each ancestor in class hierarchy.
Inheritance and encapsulation interact with each other. If a given class encapsulates some attributes, any of its child classes will have the same attributes, and also add its own unique attributes (see-2 ). This is a key concept of linear rather than geometric growth in the complexity of object-oriented programs. The new subclass inherits all attributes of all its ancestors. It does not have unexpected interactions with most of the Code in the system.
Polymorphism
Polymorphism (Polymorphism, from Greek, indicating "multiple forms") is a feature that allows an interface to be used by multiple similar actions. The specific action used is related to the application scenario, next we will take a post-import, first-out stack as an example. Suppose you have a program that requires three different types of stacks. A stack is used for integer, a floating point, and a character. Although the data types stored in the stack are different, the algorithms for implementing each stack are the same. If you use a non-object-oriented language, you need to create three different stack programs with one name for each program. However, if you use Java, you can create a common stack Assembly because of its polymorphism, and they share the same name.
The concept of polymorphism is often said to be "an interface, multiple methods ". This means that a common interface can be designed for a group of related actions. Polymorphism allows the same interface to be used by multiple actions of the same class, thus reducing the complexity of the program. Selecting a specific action (method) that is applied to each scenario is a compiler task, and programmers do not need to manually select it. You only need to remember and use common interfaces.

-2 The drag-and-drop hound inherits all its superclass.
In comparison to a dog, the smell of a dog is polymorphism. If a dog smells like a cat, it will bark and chase it. If a dog smells food, it will produce saliva and run toward the bowl where the food is filled. In both cases, the same smell organ is working. The difference is what the smell is, that is, there are two different types of data acting on the dog's nose! This general concept can also be used when using methods in a Java program.
Interaction between polymorphism, encapsulation, and inheritance
If used properly, you can write programs that are more robust and more scalable than the process-oriented model environment in a programming environment composed of polymorphism, encapsulation, and inheritance. A well-designed class hierarchy is the basis for reusing programs that you have spent time and effort improving and testing, encapsulation allows you to upgrade and migrate programs without disrupting code dependent on common interfaces. polymorphism helps you Write clear, easy to understand, easy to read, and easy to modify programs.
In the previous two examples related to real life, cars can fully describe the advantages of object-oriented design. It is also interesting to use dogs to introduce inheritance. In general, cars are very similar to programs, and all drivers rely on inheritance to quickly master the technology of driving different types of (subclass) vehicles. Whether it's a school bus, a mosidis private car, a Porsche car, or a family car, drivers can almost find the steering wheel, brakes, and accelerators and know how to operate. After a drive, most people even know the difference between the manual and the automatic shift, because they fundamentally understand the super-drive of the two stalls.
What people see on cars is always encapsulated. The brakes and footboards hide incredible complexity, but the interface is so simple that you can operate on them! The size of the engine, brakes, and tires does not have any impact on how you define foot boards.
The final attributes and polymorphism are fully reflected in the capabilities of vehicle manufacturers to provide multiple choices based on the same transport. For example, there are two types of brake systems: positive and reverse locks. The steering wheel can be divided into four-cylinder, six-cylinder, or eight-cylinder engines. Regardless of the settings, you have to step on the brakes to stop, turn the steering wheel to turn, and press the clutch to brake. The same interface can be used to control many different implementation processes.
As you can see, through the principle of encapsulation, inheritance and polymorphism, each independent part forms the car object. This is also true in computer programming. Through the use of object-oriented principles, various complex parts of the program can be combined into a consistent, robust, and maintainable program as a whole.
As mentioned at the beginning of this section, all Java programs are object-oriented. Or, more precisely, each Java program has encapsulation, inheritance, and polymorphism. Although these features are not reflected in the simple sample programs to be introduced in this chapter and the sample programs in subsequent chapters, they are also reflected. You will see that many of the features provided by Java are part of its built-in class library, which makes encapsulation, inheritance and polymorphism more widely used.
Related Article

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.