Java basics 08 inheritance

Source: Internet
Author: User

Java basics 08 inheritance

Inheritance is an important object-oriented concept. Inheritance is another important way to improve reusibility in addition to composition. In composition, we can see that a combination is a function interface that repeatedly calls an object. We will see that inheritance can reuse existing class definitions.

Class inheritance

When we define a class, we define each member of the class from the beginning. 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 this class: The data members of this class, the methods of this class, and the interfaces of this class.

 

Now we need to define a new class, such as the Woman class, and assume that the Woman and Human classes are quite similar:

We can define the Woman class from the beginning as before:
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 has a lot of troubles when writing the above program. Many definitions have been written in the Human class, but we need to repeat them. The Woman class only adds a giveBirth () method (this method is created and a new Human object is returned ).

 

With inheritance, we can avoid the above repetition. Given that the Woman class inherits from the Human class, the Woman class automatically has all the public members of the Human class.

We use the extends keyword to represent inheritance:

class Woman extends Human{    /**     * new method     */    public Human giveBirth()    {        System.out.println("Give birth");        return (new Human(20));    }}
In this way, we can save a lot of input. Through inheritance, we create a new class called the evaluate class ). The inherited class (Human) is called the base class ). The category class uses the base class as its own basis, and supplements the giveBirth () method not defined in the base class. The inheritance relationship can be expressed as follows: You can Test it using the following Test class:
public class Test{    public static void main(String[] args)    {        Woman aWoman = new Woman();        aWoman.growHeight(120);        System.out.println(aWoman.getHeight());                                                 }}

Derivative Layer

Through inheritance, we created the Woman class. The entire process can be divided into three levels: basic class definition, category class definition, and external use.

 

The hierarchy of the base class definition is a normal definition of a class, such as the above definition of the Human class.

In the view of external users (such as creating Woman class objects in the Test class), The Role class has a unified external interface:

 

This interface is sufficient for external users. From the interface alone, the category class has nothing special.

 

However, when programmers define the hierarchy of the category class, they must be careful:

First, the interfaces are mixed: the getHeight () method and the growHeight () method come from the base class, while the giveBirth () method is defined inside the Birth class.

More complicated. We can use this to refer to objects in the class ). However, when we define the Woman class, we cannot access the private member of the base class Human. We remember the meaning of private: private Members are only for internal use of this class. The Woman class is a new class different from the Human class, so it is located outside the Human class. In the category class, you cannot access the private Members of the base class.

But interestingly, our growHeight () and getHeight () methods can still run. This indicates that the private member of the base class exists, but we cannot directly access it.

To clarify the concept, we need to understand the generation mechanism of entity class objects. When we create a parent class object, Java first creates a base class Object (subobject) and is outside the base class Object (note that this is the external of the base class object, and add other members of the struct class definition to form a struct class object. What the external user can see is the public Member of the base class and category class. For example:

The yellow color in the base class object and category class object graph is the base class object. Members at the grassroots level can access each other (this in the definition of the Human class refers to the base class object ).

The blue part is the new content of the derivative object, which is called the derivative layer. The blue and yellow parts form derivative objects. Members of the derivative layer can access each other (this in Woman's definition ). Furthermore, we can also access public members at the grassroots level. For this reason, we use the super keyword to refer to the base class object, and use the super. member method to represent the basic (public) member.

When we are at the derivative layer (that is, when defining the Woman class), we cannot access the red grass-roots private members. When we are outside, we can neither access the private Members of the purple derivative layer nor the Grass-roots private members in red. (The private member of the derivative layer has access prohibitions, so it is marked as a diagonal line. Private Members at the grass-roots level have the most access prohibitions, so they are marked as diagonal lines)

Similar to this, super is also an implicit parameter. This has different meanings when we define different levels of classes. Be careful when using the this and super keywords.

(Java does not force the use of this and super. In many cases, Java can automatically identify the owner of a member. But I think this is a good habit .) Protected

We previously introduced two keywords related to access permissions, private and public, which control the external visibility of members. Now, we will introduce a new access permission Keyword: protected.

The member marked as protected is visible in this class and its protected class. This concept is easy to understand, that is, the protected member of the base class can be accessed by the derivative layer, but cannot be accessed by the external, such:

Method coverage

The external interface of a category object is composed of the public Member of the base class object and the public Member of the derivative layer. If the public member of the base class has the same name as the public Member of the derivative layer, which one is displayed in the Java interface?

We have mentioned in constructor methods and method overloading that Java uses both the method name and parameter list to determine the method to be called. The method is determined by the method name and parameter list. In the above problem, if the method name is the same and the parameter list is different, the two methods will be presented to the interface at the same time, which will not cause us any trouble. During external calls, Java determines which method to use (method overloading) based on the provided parameters ).

What if the method name and parameter list are the same? At the derivative layer, we can also use super and this to determine which method is used. In the external environment, we only present a unified interface, so we cannot provide two methods at the same time. In this case, Java will present the method of the derivative layer, rather than the method of the grass-roots layer.

This mechanism is called method overriding ). Method override can be used to modify the methods of base class members. For example, in the derivative layer, that is, when Woman is defined, you can modify the breath () method provided by the base class:

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: At this time, we are at the derivative layer, and we can still use super to call the breath () method of the base class object. When we call the Woman class externally, the method of the base class object cannot be called due to method overwrite.

The method overwrite maintains the interface of the base class object, and uses the implementation of the derivative layer. After understanding the concepts of the base class object and the derivative layer, the constructor of the category class is easy to understand.

We need to define the constructor with the same name as the class in the definition of the category class. In this constructor:

Because the base class object is first created and initialized when a derivative object is created, the base class constructor should be called first. We can use the super (argument list) statement to call the construction method of the base class.
After the base class object is created, start to build the derivative layer (initialize the derivative layer member ). This is the same as the general build method. Refer to the constructor and method overload.


For example, in the following program, the Human class has a constructor:
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; }
Woman class definition and constructor:
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...");    }}
Summary

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.