The thinking Logic of computer program (17)-The basic principle of inheriting implementation

Source: Internet
Author: User
Tags instance method

In the 15th section we introduce the basic concepts of inheritance and polymorphism, while the last section introduces some of the details of inheritance, and in this section we introduce the basic principles of inheritance implementations in an example. It is important to note that this section mainly introduces the principle from the concept, the actual implementation details may differ from this.

Example

This is the base class code:

 Public classBase { Public Static ints; Private intA; Static{System.out.println ("Base class static code block, S:" +s); S= 1; } {System.out.println ("Base class instance code block, a:" +a); A= 1; }         PublicBase () {System.out.println ("Base class construction method, a:" +a); A= 2; }        protected voidStep () {System.out.println ("Base S:" + S + ", A:" +a); }         Public voidaction () {System.out.println ("Start");        Step (); System.out.println ("End"); }}

Base includes a static variable s, an instance variable a, a static initialization code block, an instance initialization code block, a construction method, two methods step and action.

This is the subclass code:

 Public classChildextendsBase { Public Static ints; Private intA; Static{System.out.println ("Subclass static code block, S:" +R); S= 10; } {System.out.println ("Subclass instance code block, a:" +a); A= 10; }         PublicChild () {System.out.println ("Subclass constructor Method, a:" +a); A= 20; }        protected voidStep () {System.out.println ("Child S:" + S + ", A:" +a); }}

Child inherits base, also defines a static variable s and instance variable A with the same name as the base class, static initialization code block, instance initialization code block, constructor method, and override method step.

This is the code used:

 Public Static void Main (string[] args) {    System.out.println ("----New Child ()");     New Child ();        System.out.println ("\ n----c.action ()");    C.action ();         = C;    System.out.println ("\ n----b.action ()");    B.action ();            System.out.println ("\ n----B.S:" + B.S);     System.out.println ("\ n----C.S:" + C.S);}

An object of type child was created, assigned the reference variable C of the child type, called the action method by C, and assigned the reference variable B of the base type, the action is also called through B, and the static variable s is then exported through B and C. This is the result of the screen output:

----new Child () base class static code block, s:0 subclass static code block, s:0 base class instance code block, a:0 base class construction method, A:1 subclass instance code block, a:0 subclass construction method, a:10----c.action () StartChild s: Ten, A:20end----b.action () startchild s:10, a:20end----b.s:1----c.s:10

Let's explain what's going on behind the scenes, starting with the loading of classes.

Loading of classes

In Java, the so-called load of a class refers to loading information about a class into memory. In Java, classes are dynamically loaded, loaded when the class is first used, and when a class is loaded, the parent class is checked to see if it is loaded, and if not, the parent class is loaded.

The information for a class consists mainly of the following sections:

    • class variables (static variables)
    • Class initialization code
    • class method (static method)
    • Instance variable
    • Instance initialization code
    • Instance method
    • Parent class Information Reference

The class initialization code consists of:

    1. Assignment statement when defining a static variable
    2. Static initialization of code blocks

The instance initialization code consists of:

    1. Assignment statement when defining an instance variable
    2. Instance initialization code block
    3. Construction method

The class loading process includes:

    1. Allocating information for memory-saving classes
    2. Assigning default values to class variables
    3. Load Parent class
    4. Set up parent-child relationships
    5. Executing class initialization code

It is necessary to note that the class initialization code executes the parent class first and then executes the subclass, however, when the parent class executes, the value of the subclass static variable is also the default value. For the default value, as we said before, the numeric variable is 0,boolean False,char is ' \u0000 ' and the reference variable is null.

As we said before, the memory is divided into stacks and heaps, the stack holds the local variables of the function, and the heap holds the dynamically allocated objects, and a memory area, which holds the information of the class, which is called the method area in Java.

After loading, for each class, in the Java method area there is a copy of this class of information, in our case, there are three classes of information, namely, Child,base,object, memory is as follows:

We use Class_init () to represent the class initialization code, with Instance_init () representing the instance initialization code, the instance initialization code includes the instance initialization code block and the construction method. There is only one construction method in the example, and there may be multiple instance initialization methods in practice.

In this example, the class is loaded in memory like a layout similar to the above, and then executes the class initialization code for base and child, respectively. Next, we look at the process of object creation.

Creating objects

After the class is loaded, new child () is the creation of the child object, and the process of creating the object includes:

    1. Allocating memory
    2. Assigning default values to all instance variables
    3. Executing instance initialization code

The allocated memory includes instance variables for this class and all parent classes, but does not include any static variables. The execution of the instance initialization code starts with the parent class, executes the parent class first, and then executes the child class. However, all instance variables are set to their default values before any class executes the initialization code.

Each object holds a reference to the actual class information in addition to the instance variables of the class.

Child C = new Child (); The newly created child object reference is assigned to the variable C, and base B = C; The child object is also referred to by B. After creating and assigning values, the memory layout is probably as follows:


The reference variables C and B are allocated on the stack, pointing to the child object in the same heap, the child object stores the address of the child type in the method area, and the instance variable a in base and instance variant A in child. Create the object, and next, look at the procedure called by the method.

Method Invocation

Let's take a look at c.action (); The execution of this code is:

    1. Look at the object type of C, find the child type, find the action method in the child type, find no, find in the parent class
    2. Method action found in parent class base, start execution action method
    3. Action first outputs start and then discovers that the step () method needs to be called, starting with the child type to find the step method
    4. The step () method is found in the child type, the step () method in child is executed, and the action method is returned after execution
    5. Continue with the action method, output end

when looking for an instance method to execute, it starts with the actual type information of the object and finds the parent class type information when it is not found.

Let's see b.action (); the output of this code is the same as the c.action, which is called dynamic binding, and the mechanism for dynamic binding implementation is to find the method to execute based on the actual type of the object, and then find the parent class when it is not found in the subtype. here, because B and C point to the same object, the execution result is the same.

If the inherited hierarchy is deep and the method to be called is in the parent class of the upper layer, the invocation is inefficient because each call is searched many times. Most systems use a method called virtual method tables to optimize the efficiency of calls.

Virtual method Table

The so-called virtual method table, when the class is loaded, creates a table for each class that includes all the dynamically bound methods of the class's objects and their addresses, including the methods of the parent class, but only one record for a method, and only the subclass is preserved when the subclass overrides the parent class method.

For this example, the virtual method table for child and base is as follows:


For the child type, the action method points to the code in base, the ToString method points to the code in object, and step () points to the code in this class.

This table is generated when the class is loaded, and when the method is dynamically bound through the object, it is only necessary to find the table, instead of looking for each parent class.

Next, we look at the access to the variable.

Variable Access

Access to a variable is statically bound , whether it is a class variable or an instance variable. The code demonstrates class variables: B.S and C.S, which access class variables through objects, and the system translates to direct access to class variables Base.s and Child.s.

The instance variables in the example are private and cannot be accessed directly, and if it is public, B.A accesses the instance variable a defined by the base class in the object, and C.A accesses the instance variable a defined by the child class in the object.

Summary

In this section, we present an example of the internal process of loading, object creation, method invocation, and variable access for a class. Now, we should have a relatively clear understanding of the implementation of inheritance.

As we mentioned before, inheritance is actually a double-edged sword, why do you say so? Let's discuss it in the next section.

----------------

To be continued, check out the latest articles, please pay attention to the public number "old Horse Programming" (Scan the QR code below), from the introduction to advanced, in layman's words, Lao Ma and you explore the nature of Java programming and computer technology. Original article, All rights reserved.

The thinking Logic of computer program (17)-The basic principle of inheriting implementation

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.