Dark Horse Programmer--Object oriented

Source: Internet
Author: User

------<a href= "http://www.itheima.com" target= "blank" >java training, Android training, iOS training,. NET training </a>, look forward to communicating with you! -------

This article is a summary and review of the Java object-oriented concept. Object-oriented is an important feature of the Java language, only a real Java programmer is a true understanding of the basic concepts of object-oriented and the application of object-oriented concepts to write Java programs.

I. Object-oriented Concepts

Object-oriented is relative to process-oriented, object-oriented and process-oriented is a kind of thought. Process-oriented emphasis is on functional behavior, just as our familiar C language is the language of the face process. Object-oriented encapsulates functionality into objects, emphasizing functional objects, just like the Java language.

We illustrate the process-oriented and object-oriented differences with an example of loading an elephant into a refrigerator.

Process oriented:

1. Open the refrigerator door

2. Load the elephant in

3. Close the refrigerator door

"Open", "save", "close" are functional behavior, the visual embodiment in code is a function or method, which is a process-oriented concept of functional behavior as the main embodiment.

Object-oriented: Encapsulates the method into a refrigerator object.

1. Open the refrigerator

2. The refrigerator is loaded with elephants

3. Refrigerator closed

As you can see, all operations are based on the "refrigerator" instead of the functional behavior. In other words, the refrigerator itself already has the "open", "storage", "close" behavior function, we only need to let the refrigerator perform its functions can be. This is an object-oriented embodiment of the object of execution function as the main body.

Object-oriented is a kind of thought that conforms to people's thinking habits, which can simplify complicated things and convert programmers from performers to conductors.

In terms of object-oriented thinking, the process of solving the problem is:

1, first to find the desired function of the object to use.

2. If the object does not exist, create an object with the required functionality.

This simplifies development and improves reuse. So the process of developing in an object-oriented world is to constantly create objects, use objects, and direct objects to do things. The design process is to manage and maintain the relationships between objects. Object-oriented has three major characteristics: encapsulation, inheritance, polymorphism.

Second, class and object

The use of computer language is constantly in the description of real life things, Java describes things through the form of classes, classes are the abstract of concrete things. An object is an individual that has a real existence for that kind of thing.

Simply put, a person is an abstract concept, is a class, refers to the nature of people with the characteristics of the individual collectively. And every living person in life is an object, except that the object has a common attribute, but also has the unique attribute of each individual.

Describing things in life is nothing more than describing the properties and behaviors of things. The same is true of Java using class classes to describe things. Property: The member variable in the corresponding class; behavior: A member function in the corresponding class. Then the definition class actually defines the members (member variables and member functions) in the class.

For example, we describe the car, the car has color, and a few wheels, then we define the class structure as follows:

1 classCar2 {3      PublicString color;//The car has color .4      Public intNumber//Number of wheels5      PublicCar ()//6     {7Color= "Red";//assigning an initial value in a constructor8Number=4;9     }Ten      Public voidShow ()//How to display a class One     { ASystem.out.println ("Color:" +color+ "--num:" +Number ); -     } -}

There is a property in the class above, and there is a method where the constructor has no return value and has the same name as the class.

So then we'll create the object through the class.

The code for creating the object is as follows:

1     Car c1=new  car (); 2     C1.color= "Blue"; 3     Car c2=new  car (); 4     c1.show (); 5     C2.show ();            

The format for creating objects in memory is as follows:

  

As long as the entity defined with the new operator opens up a new space in the heap memory, and each object has its own attribute. After space is opened, assign the address to a variable of class type. C1, C2 Two class variables point to different class memory spaces.

The members of an object are manipulated by the way they are members of an object, and the members of one object are modified to have no relation to the other object. Just as the value of color in memory as above C1 is changed to blue and the value of the color attribute in C2 does not change.

When C1 and C2 no longer point to the object, if the object does not have any variables that point to his class type, the object is cleaned up by the garbage collection period at a certain time period.

Well, we've analyzed the creation of objects in memory, so let's run the program and see if the results are the same as our analysis.

The results of the program run are as follows:

  

  Anonymous objects

  An anonymous object is a simplified way of objects, two usage of anonymous objects: 1. When only one call is made to an object method, such as: New Car (). Show (), 2, 2. Anonymous objects can be passed as actual parameters. Pass the new car () as a parameter to manipulate the data of the car class inside the function.

  Basic data type parameters and reference data type parameter passing

In Java, the pass of a method parameter is always passed, and this value, for the base data type, is the value you assign to the variable. For reference data types, this value is the object's reference, not the object itself.

Let's take a look at the difference between the two by code:

  

1 classMyClass2 {3      Public Static voidMain (string[] args)4     {5         intNum=4;6Car c1=NewCar ();7Show (num);//passing the base data type as a parameter8Show (C1);//passing the application data as a parameter9SYSTEM.OUT.PRINTLN ("Basic data type, before delivery is 4, after passing is:" +num);TenSYSTEM.OUT.PRINTLN ("Reference data type, before pass is 4, is passed after:" +c1.num);  One     } A     Static voidShowintnum) -     { -num=2; the     } -     Static voidShow (Car c) -     { -c.num=2; +     } -}

The result of the output is:

  

You can see that the data has changed since the reference data type was passed as a parameter, and the two basic data types have not changed.

Three, Package

  Encapsulation: Refers to the properties and implementation details of hidden objects, providing public access only to the outside.

Benefits of Encapsulation: 1. Isolate the change. 2, easy to use. 3, improve reusability. 4, improve security.

Encapsulation principle: 1, will not need to provide external content is hidden.

2, the property is hidden, provide public methods to access it. For example, Getxxx,setxxx.

Private is only a manifestation of encapsulation.

Four, the constructor function

Function: initializes the object.

Features: 1, Function name and class name are the same, 2, do not define the return value type, 3, no specific return value

The difference between a constructor and a normal function:

Constructor: When an object is created, the corresponding constructor is called and the object is initialized. Called only once.

General functions: When an object is created, it is called when a function function is required. Can be called multiple times.

If a constructor is not defined in a class, there is a default null argument constructor in the class. If the specified constructor is defined in a class, the default constructor in the class is gone. Constructors exist in an overloaded form.

Five, this keyword

This represents a reference to the object to which the function belongs. In other words, this is a reference to this class of objects. When a member variable and a local variable have the same name, it can be distinguished by the keyword this, which is the reference to the object to which the function belongs. In short, which object calls the function where this is located, this represents which object. The general method calls the default plus this. Use this when you need to use the object that calls the function within a function.

This can only be defined on the first line of the constructor when invoking other constructors in the constructor, because the initialization action is executed first, or an error is given. This is a good understanding, if it is not in the first row, then we have done before the initialization of the action may be overwritten and invalid.

VI. Static keyword

  Static keyword: used to decorate members (member variables and member functions).

  The modified members have the following characteristics:

1. Load with the load of the class.

2, precedence over the existence of the object.

3. Shared by all objects.

4, can be directly called by the class name.

The difference between a member variable and a static variable

1, two variables have different life cycles

Member variables exist as objects are created and released as objects are recycled.

Static variables exist as the class loads, disappearing as the class disappears.

2. Different calling methods

Member variables can only be called by an object.

A static variable can be called by an object and can also be called by a class name.

3. Different aliases

Member variables are also known as instance variables.

A static variable is also known as a class variable.

4. Different Data storage locations

      Member variables are stored in the object of the heap memory, so they are also called object-specific data.

Static variable data is stored in the static area of the method area (shared data area), so it is also called the shared data of the object.

Note: Static methods can only access static members, and if you access non-static members, you will get an error! The reason is well understood that static methods are loaded as the class loads, and no objects are created at this time, so non-static members cannot be accessed. This is understood by the fact that non-static methods can either orient non-static members or access static members.

The main function is static, the main function is a special function, as we mentioned before, main is not a keyword, specifically the main function is as follows: 1, the format is fixed, public static void main (string[] args). 2. Recognized and called by the Java Virtual machine.

Having learned so much about static characteristics, when is static used?

1. Static variables

When the values of the member variables in the parsed object are the same, the member can be statically decorated. As long as the data in the object is different, is the object's unique data, must be stored in the object, is non-static. If the same data, the object does not need to make changes, only need to use, do not need to store in the object, defined as static.

2. Static function

Whether a function is statically decorated, it is a reference to whether the function requires access to the unique data in the object. To put it simply, from the code point of view, whether the function needs to access non-static member variables, if necessary, the function is non-static. If you do not need it, you can define the functionality as static. Of course, it can also be defined as non-static, but non-static needs to be called by the object.

Static code blocks initialize the class and construct blocks of code to initialize all objects.

Knowledge Point Expansion: 

The initialization process for an object:

What do you do to define a new object?

1. Load the class name. class file into memory.

2. Execute the static block of code in the class and initialize the class if you have something to do.

3. Open up space in heap memory, allocate memory address to object.

4. Establish the unique properties of the object in heap memory and initialize it by default.

5, the property is displayed initialization.

6, the object is constructed code block initialization.

7. Initialize the corresponding constructor for the object.

8. Assign the memory address to the object name variable in the stack memory.

  Single Case design mode

Design pattern is the idea of solving a kind of problem. A single-instance design pattern solves the problem of ensuring that a class's object uniqueness in memory is guaranteed. For example, when multiple programs use the same configuration information object, it is necessary to guarantee the uniqueness of the object.

The idea of a single case design pattern:

1. Do not allow other programs to create this class object with new. ---privatization of constructors

2. To have an object of this class. ----creates an instance of this class in this class.

3. Provide a way for other programs to get the object. ----"Defines a public method that returns the created object.

The singleton pattern is divided into two ways: a hungry man and lazy.

A hungry man single-case mode:

1 classSingleclass2 {3     //a hungry man, the object is created when the class loads4     Private StaticSingleclass sc=NewSingleclass ();5     PrivateSingleclass ()6     {7     }8      Public StaticSingle getinstance ()9     {Ten         returnSC; One     } A}

Lazy single-Case design mode:

1 classSingleclass2 {3     //lazy, class-loaded object not created, created when used, also called lazy load4     Private StaticSingleclass SC;5     PrivateSingleclass ()6     {7     }8      Public StaticSingle getinstance ()9     {Ten         if(sc==NULL) OneSc=NewSingleclass (); A         returnSC; -     } -}

Lazy single-case design mode in multi-threaded times is not secure, after the code synchronization to ensure the security of multithreading.

1 classSingleclass2 {3     //lazy, class-loaded object not created, created when used, also called lazy load4     Private StaticSingleclass SC;5     PrivateSingleclass ()6     {7     }8      Public StaticSingle getinstance ()9     {Ten  One         if(sc==NULL)//make a non-empty judgment before synchronizing to improve the efficiency and security of the program A         { -             synchronized(NewObject ())//Plus sync lock -             { the                 if(sc==NULL) -Sc=NewSingleclass (); -             } -         } +         returnSC; -     } +}

This concludes the object-oriented summary, and the content of this chapter is very important. A lot of knowledge points must be understood, to master, to be able to write code to verify.

Keep on trying to refuel! For tomorrow's better self.

Dark Horse Programmer-object-oriented

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.