interface and abstract class differences.

Source: Internet
Author: User

Abstract class Dog {
abstract void eat ();
Abstract void is called ();
}
Interface Dog {
abstract void eat ();
Abstract void is called ();
}
Add a feature to narcotics. Describe a drug-suppressing function dog separately.
Class drug dog extends dog {
void Eat () {}
void called () {}
void drug () {}
}

Class drug dog implements dog {
void Eat () {}
void called () {}
void drug () {}
}
Drug dogs are a kind of dog, is a relationship.
Dogs are used to describe the basic functions of all functional dogs, defined by class. The parent class.
So dogs are not fit to be defined as interfaces.

(Background: If there are narcotics pigs, drug-narcotics robots ...) What should we do?
Now the dog, the pig, the robot all has the anti-drug this function. In order not to repeat the definition of the anti-narcotics function, we abstract it into an interface. )

Class anti-drug pig {
void drug () {}
}
There are many anti-narcotics functions. Anti-narcotics functions need to be extracted. Extracted into a class, or extracted into an interface?
Try it first and define it as a class.
Abstract class anti-narcotics {
abstract void narcotics ();
}
No, drug dogs inherit dogs, and they cannot inherit other classes, because classes cannot inherit more.

Define as interface try
Interface Anti-narcotics {
abstract void narcotics ();
}

Class drug dog extends dog implements anti-narcotics {
void Eat () {}
void called () {}
void drug () {}
}
This is possible.
Class is used to describe the common basic functions of things.
Interfaces are used to define the extra functionality of things.

interface and abstract class differences.

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.