Differences between class inheritance and class inclusion

Source: Internet
Author: User

Class inheritance and class inclusion are designed to extend the original class. (See introduce in refactoring. Foreign Method and introduce Local extension)

Inheritance is recommended in refactoring because implementation is relatively simple. However, in one case, the include clause must be used. The following is an example:

Now there is a date class. We know the structure of this class, but we cannot change this class.

Public class date

{

Int y, M, D;

Public date (INT _ y, int _ m, int _ d)

{

Y = _ y;

M = _ m;

D = _ d;

}

}

Now we want to use the date class with a nextdate () method, so that we can get the next day of the date. The following is the mydate class extended using an inherited method:

Public class mydate: Date

{

Public mydate (INT y, int M, int D): Base (Y, M, d)

{

}

Public mydate nextdate ()

{

D = d + 1;

Return this;

}

}

The code for calling the mydate class is as follows:

Mydate MD = new mydate (datetime. Now. Year, datetime. Now. Month, datetime. Now. Day );

.......

Mydate mdnext = md. nextdate ();

An error occurs in this Code::

The initialization time is-7-7. When the initialization function is executed but the nextdate () function is not executed, the current time is-7-8, but the returned nextdate () still 2007-7-8 (should be 2007-7-7-9)

If you change inheritance to include, this problem will not occur. The following code is changed to include:

Public class mydate

{

Int y, M, D;

Date D;

Public mydate ()

{

}

Public date nextdate ()

{

Date d = new date (Y + 1, m + 1, D + 1 );

Return D;

}

}

The call code is as follows:

Mydate MD = new mydate ();

.......

Md. Y = datetime. Now. Year;

Md. M = datetime. Now. month;

Md. d = datetime. Now. Day;

Date mdnext = md. nextdate ();

You can also see:The inherited object must be initialized when its subclass is initialized. The inclusion feature can be initialized at other times..

Reprinted, please indicate the author and Source

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.