Java Vamei Quick Tutorial 08 Inheritance

Source: Internet
Author: User
Tags class definition

Vamei Source: Http://www.cnblogs.com/vamei Welcome reprint, Please also keep this statement. Thank you!

Inheritance (inheritance) is an important object-oriented concept. Inheritance is another important way to improve code repeat availability (reusibility) in addition to composition (composition) . As we see in the composition (composition), the combination is the functional interface that invokes the object repeatedly. As we'll see, inheritance can reuse the definition of an existing class .

Inheritance of Classes

When we first defined the class, we started from scratch and defined each member of the class in detail. For example, the following human class:

Class human{      /**     * accessor * * * public    int getheight ()    {       return this.height;    }    /**     * mutator     *    /public void growheight (int h)    {        this.height = this.height + h;    }
/**
* Breath
*/
public void Breath ()
{
System.out.println ("hu...hu ...");
} private int height;}

From the above class definition, we can understand all the details of the class: the class's data member, the class's method, the interface of the class.

Now define a new class, such as the woman class, and assume that woman is quite similar to the human class:

Human & Woman

We can, as before, start from the beginning and complete the definition of the woman class:

Class woman{    /**     * accessor * * * public    int getheight ()    {       return this.height;    }    /**     * mutator     *    /public void growheight (int h)    {        this.height = this.height + h;    }
    /**
* Breath
*/
public void Breath ()
{
System.out.println ("hu...hu ...");
} /** * New method */public Human Givebirth () { System.out.println ("Give birth"); Return (new Human); } private int height; }

A programmer in writing the above program, there will be a lot of trouble. Many of the definitions have been written in the human class, but we have to knock them out again. The woman class adds only one Givebirth () method that creates and returns a new human object.

With inheritance, we can avoid the repetition above. Having the woman class inherit from the human class, the woman class automatically has the functionality of all public members in the human class.

We use the extends keyword to denote inheritance:

Class Woman extends human{
/** * New method */public Human Givebirth () { System.out.println ("Give birth"); Return (new Human);} }

In this way, we save a lot of input. Through inheritance, we created a new class called the derived class (derived classes). The inherited class (Human) is called the base class. The derived class bases its own definition on the base class and complements the Givebirth () method that is not defined in the base class. An inheritance relationship can be expressed as:

Inheritance: Arrows point to base class

You can use the following test class tests:

public class test{public    static void Main (string[] args)    {        Woman Awoman = new Woman ();        Awoman.growheight (+);        System.out.println (Awoman.getheight ());}                                                 }

Derivative layer

Through inheritance, we created the woman class. The entire process can be divided into three levels: base class definition, derived class definition, external use .

The hierarchy defined by the base class is the normal definition of a class, such as the human class definition above.

In the view of external users (such as creating a woman class object in the test Class), the derived class has a uniform external interface:

For external users, the above interface is sufficient. In terms of interfaces only, derivative classes are nothing special.

However, when programmers are at the level defined by a derived class , they must be careful:

First, the interfaces are mixed: the GetHeight () method and the Growheight () method come from the base class, and the Givebirth () method is defined inside the derived class.

There are more complicated places. We previously had the freedom to access members of the class (using this Reference object) inside the class. However, we cannot access the private members of the base class human when we are within the scope of the definition of the woman class. We remember the meaning of private: Private members are used only within that class. The woman class is a new class that differs from the human class, so it is outside the human class. In a derived class, you cannot access the private members of the base class.

But interestingly, our growheight () and GetHeight () methods can still be run. This indicates that the private member of the base class exists and we just cannot access it directly .

For clarity, we need to understand the generative mechanism of the derived class object. When we create an object of a derived class, Java actually creates a base class object (Subobject), and outside of the base class object (note, here is the outside of the base class object, the inside of the derived class object), adding other members of the derived class definition, constituting a The derived class object . The public members of the base class and the derived class can be seen by the external user. Such as:

Base class objects and derived class objects

The yellow in the figure is the base class object. Members of the grass-roots can access each other (using the this in the human class definition to refer to the base class object).

The blue part is the new content of the derivative object, which I call the derivative layer. The blue and yellow parts together form the derivative object. Members of the derived layer can access each other (this in the woman definition). Further, we can also access members of public at the grassroots level. To do this, we use the Super keyword to refer to the base class object, using the Super.member method to represent the grassroots (public) members.

When we are in the derived layer (that is, when we define the woman class), we cannot access the red grass-roots private members. When we are outside, we cannot access either the private members of the purple derived layer or the red grass-roots private members.

(The private member of the derived layer has access taboos, so it is marked as a slash.) Grassroots Private member access Taboo most, so labeled as cross Slash)

Super is similar to this and is also an implicit parameter . This will have different meanings when we are at different levels of the class definition. Be careful with the This and Super keywords.

(Java does not enforce the use of this and super.) In many cases, Java can automatically identify the attribution of a member. But I think it's a good habit. )

Protected

We have previously covered two access-related keywords, private and public, which control the external visibility of members. Now, let's introduce a new access keyword: protected.

A member labeled protected is visible in the class and its derived classes. This concept is easy to understand, that is, the protected members of the base class can be accessed by the derived layer, but cannot be accessed externally, such as:

Method overrides

The external interface of the derived class object is ultimately composed of the public member of the base class object and the public member of the derived layer. If the base class public member and the public member of the derived layer have the same name, which one is rendered in the Java interface?

As we have already mentioned in the constructor and method overloads, Java is the method by which the method name and the parameter list are used to determine which methods to invoke. method is determined by both the method name and the parameter list. In the above problem, if only the method name is the same, and the parameter list is different, then two methods will be presented to the interface at the same time, will not cause us trouble. When externally invoked, Java determines which method (method overload) to use, based on the parameters provided.

What if the method name and argument list are the same? In the derivation layer, we can also use super and this to determine which method. On the outside, we only present a unified interface, so we cannot provide two methods at the same time. In this case, Java renders the method of the derived layer, not the grass-roots approach.

This mechanism is called method overriding. Method overrides can be well exploited to modify the methods of a base class member. For example, the breath () method provided by the base class can be modified when the derived layer, or woman, is defined:

Class Woman extends human{/**     * New method */public    Human Givebirth ()    {        System.out.println ("Give Birth ");        Return (new Human);    }    /**     * Override Human.breath () */public    void Breath ()    {        super.breath ();        System.out.println ("su ...");}    }

Note that at this point we are in the derived layer and can still invoke the breath () method of the base class object through Super. When we call the woman class externally, it is no longer possible to call the method of the base class object because of the method override.

The method overrides the interface of the base class object, and adopts the implementation of the derived layer.

Construction method

After understanding the concepts of the base class object and the derived layer, the construction method of the derived class is easier to understand.

We want to define a construction method with the same name as the class in the definition of the derived class. In this construction method:

    • Because the base class object is created and initialized first when the derived object is created, the constructor of the base class should be called first. We can use the Super (argument list) statement to invoke the constructor method of the base class.
    • After the base class object is created, start building the derived layer (initializing the derived layer member). This is the same as the general construction method, with reference to construction methods and method overloading

For example, in the following program, the human class has a constructor method:

Class human{   
    /**     * constructor * *     
Public Human (int h)
{
This.height = h;
}
/** * Accessor * /public int getheight () { return this.height; } /** * mutator * /public void growheight (int h) { this.height = this.height + h; }
/**
* Breath
*/
public void Breath ()
{
System.out.println ("hu...hu ...");
} private int height;}

The definition of the woman class of the derived class and its construction method:

Class Woman extends human{    /**     * constructor * * Public    Woman (int h)    {        super (h);//base class Constructor        System.out.println ("Hello, pandora!");    }    /**     * New method */public    Human Givebirth ()    {        System.out.println ("Give birth");        Return (new Human);    }    /**     * Override Human.breath () */public    void Breath ()    {        super.breath ();        System.out.println ("su ...");}    }

Summarize

Extends

Method overriding

Protected

Super.member, Super ()

Welcome to the "Java Quick Tutorials" article series

Java Vamei Quick Tutorial 08 Inheritance

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.