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.