Through the study of several previous articles, beginners can master the concept of inheritance in the Java language and the use of methods, the use of abstract classes have some understanding. It is noteworthy that the inheritance of classes and classes in Java is a single inheritance, that is, a subclass can inherit at most one parent class. So let's look at the example below.
Let's say we're going to develop a game system with three kinds of aircraft: airplanes, birds, Spider-Man. These three kinds of aircraft all need to realize the logic of Take-off, flight, descent, but the implementation methods are different. Then these three classes should have an abstract class as the parent class that regulates the common behavior.
Package com.csst.inter;
Public abstract class Flyer {public
abstract void takeoff ();
public abstract void Fly ();
public abstract void Land ();
}
Package com.csst.inter;
public class Spiderman extends Flyer {
@Override public
void Fly () {
//TODO auto-generated method stub
@Override public
void Land () {
//TODO auto-generated method stub
}
@Override
public void takeoff () {
//TODO auto-generated method stub
}
}
//Plane,bird omitted
Let's take a closer look at flyer, which is characterized by no concrete methods, all methods are abstract, and there are no variables. And if the Spiderman class needs to inherit another parent class, it cannot, because inheritance in the Java language is a single inheritance. If the Spiderman does not inherit the flyer class, it is not possible, because all aircraft are regulated by the flyer type. In order to solve the problem of single inheritance in Java, there is the concept of interface in Java. We can modify the above code as follows:
Package com.csst.inter;
Public interface Flyer {
public void Takeoff ();
Public void Fly ();
Public void Land ();
}
Package com.csst.inter;
public class Spiderman implements Flyer {public
void Fly () {
//TODO auto-generated method stub
}
Pub lic void Land () {
//Todo auto-generated method stub
} public
void takeoff () {/
/TODO auto-generated Method Stub
}
}