The difference between interface and abstract class (ii)

Source: Internet
Author: User

Requirement One: Ordinary door

Version 1.0

Abstract class Door {    publicabstractvoid  open ();      Public Abstract void close ();} class extends Door {    @Override    publicvoid  open () {}    @Override      Public void close () {}}

Version 2.0

Abstract Interface Door {    publicabstractvoid  open ();      Public Abstract void close ();} class Implements Door {    publicvoid  open () {}    publicvoid  Close () {}}

Demand two: Alarm door

Version 1.0

Abstract classDoor { Public Abstract voidopen ();  Public Abstract voidClose ();  Public Abstract voidalarm ();}classNormaldoorextendsDoor {@Override Public voidopen () {} @Override Public voidclose () {} @Override Public voidalarm () {}}

Version 2.0

Abstract InterfaceDoor { Public Abstract voidopen ();  Public Abstract voidClose ();  Public Abstract voidalarm ();}classNormaldoorImplementsDoor { Public voidopen () {} Public voidclose () {} Public voidalarm () {}}

Version 3.0

Abstract classDoor { Public Abstract voidopen ();  Public Abstract voidclose ();}Abstract Interfacealarm{ Public Abstract voidalarm ();}classNormaldoorextendsDoorImplementsAlarm {@Override Public voidopen () {} @Override Public voidclose () {} Public voidalarm () {}}

Comments:

Ordinary door, version 1.0 If you add a non-abstract method, the subclass automatically has it and does not need to change the code (advantage)

Alarm door, Version 1.0 all sub-categories, to implement the alarm, but many doors do not need to alarm (disadvantage)

Alarm, version 2.0 because the interface added an alarm function, so that all the use of the interface has to change the code, or the compilation does not pass. Disadvantage

Among the alarms, version 3.0 is the right way to handle

Interface is the abstraction of behavior, ordinary Gate 2.0 and Alarm Gate 2.0 are not appropriate.

Abstract class is an abstraction of an object, so the normal gate 1.0 is appropriate.

The difference between interface and abstract class (ii)

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: [email protected] 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.