Java Basic Tutorial Inheritance detailed _java

Source: Internet
Author: User
Tags class definition

Inheritance (inheritance) is an important concept of object-oriented. Inheritance is another important way to increase code duplication availability (reusibility) in addition to the combination (composition). We see in the composition (composition) that a combination is a functional interface that repeats the invocation of an object. We will see that inheritance can reuse the definition of an existing class.

Inheritance of Classes

When we define a class, we start from scratch and define each member of the class in detail. For example, the following human class:

Copy Code code as follows:

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 class definition above, we can understand all the details of the class: The data member of the class, the method of the class, the interface of the class.

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


Human & Woman

We can, like before, start from scratch, complete the definition of the woman class:

Copy Code code as follows:

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 (20));
}

private int height;
}

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

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

We use the extends keyword to represent inheritance:

Copy Code code as follows:

Class Woman extends Human
{
/**
* New Method
*/
Public Human Givebirth ()
{
System.out.println ("Give birth");
Return (new Human (20));
}
}

In this way, we save a lot of input. By inheriting, we create a new class called the derived class (derived class). The inherited class (Human) is called the base class. A derived class bases its own definition on a base class and supplements 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 test it with the following test class:

Copy Code code as follows:

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

Derivative layer

By inheriting, we created the woman class. The whole process can be divided into three levels: a base class definition, a derived class definition, and an external use.

The level of a base class definition is the normal definition of a class, such as the human class definition above.

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

This interface is sufficient for external users. In terms of interfaces only, there is nothing special about derived classes.

However, when programmers are at the level of deriving class definitions, they must be careful:

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

There are more complicated places. We previously had free access to the members of the class within the class (using this to refer to objects). However, when we are within the definition of the woman class, we cannot access the private members of the base class human. We remember the meaning of private: Private members only for the internal use of the class. The woman class is a new class different from the human class, so it is located outside the human class. In a derived class, private members of the base class cannot be accessed.

But interestingly, our growheight () and GetHeight () methods can still be run. This means that private members of the base class exist, and we simply cannot access them directly.

For clear concepts, we need to understand the generation mechanism of derived class objects. When we create an object of a derived class, Java actually creates a base class object (Subobject) first, and outside the base class object (note, this is the outside of the base class object, the inside of the derived class object), adding other members of the derived class definition to form a derived class object. What external users can see is the public members of the base class and the derived class. The following figure:

Base class objects and derived class objects

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

The blue section is the new content for the derived object, which I call the derivative layer. The blue and yellow parts together form the derived object. Members of the derived layer can access each other (this in the woman definition). Further, we can also access members of the public at the grassroots level. To this end, 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 derivative layer (that is, when defining the woman Class), we cannot access the red grassroots private members. When we are outside, we can neither access the purple derivative layer private members nor access the red grass-roots private members.

(The private member of the derivative layer has access taboo, so mark it as a slash.) Private members of the grassroots access the most taboo, so marked as a 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 to use this and super keywords.

(This and super are not enforced in Java.) In many cases, Java can automatically identify the attribution of a member. But I think it's a good habit. )

Protected

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

Members marked as protected are 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 not externally, as shown in the following figure:

Method overrides

The external interface of the derived class object is ultimately composed of the public members of the base class object and the public members 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 present in the Java interface?

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

What if the method name and parameter list are the same? In the derivative layer, we can also use super and this to determine which method is. While externally, we present only the unified interface, so we cannot provide two methods at the same time. In this case, Java presents the method of the derivative layer rather than the basic method.

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

Copy Code code as follows:

Class Woman extends Human
{/**
* New Method
*/
Public Human Givebirth ()
{
System.out.println ("Give birth");
Return (new Human (20));
}

/**
* Override Human.breath ()
*/
public void Breath ()
{
Super.breath ();
System.out.println ("su ...");
}
}

Note that at this point we are at the derived layer and can still invoke the breath () method of the base class object through Super. When we call the woman class externally, this method of the base class object cannot be called because of method overrides.

The method overwrites the interface of the base class object, and adopts the implementation of the derivative layer.

Construction method

After understanding the concepts of the base class object and the derivative layer, the method of constructing the derived class is also easy to understand.

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

1. Because the base class object is created and initialized first when the derived object is created, the constructor for the base class should be invoked first. We can call the constructor method of the base class using the statement of Super (argument list).

2. 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, reference construction method and method overload

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

Copy Code code as follows:

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;
}

Definition of woman class of derived class and its construction method:

Copy Code code as follows:

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 (20));
}

/**
* Override Human.breath ()
*/
public void Breath ()
{
Super.breath ();
System.out.println ("su ...");
}
}

Summarize

Extends

Method overriding

Protected

Super.member, Super ()

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.