Home >类库下载 >java类库 >Java inheritance and interfaces

Java inheritance and interfaces

高洛峰
高洛峰Original
2016-11-03 14:47:381791browse

The most critical role of interfaces is also the most important reason for using interfaces: they can be traced back to multiple basic classes. The second reason for using an interface is the same as for using an abstract base class: to prevent the client programmer from making an object of this class and specifying that it is just an interface. This brings up a question: Should I use an interface or an abstract class? If we use interfaces, we can get the benefits of abstract classes and interfaces at the same time. So if the base class you want to create does not have any method definitions or member variables, then you are willing to use an interface instead of an abstract class anyway. In fact, if you know in advance that something is going to be a base class, your first option is to turn it into an interface. Abstract classes should be considered only when method definitions or member variables must be used.

/**
 * Created by xfyou on 2016/11/3.
 * Java 继承和接口演示
 */
public class Adventure {
    static void t(CanFight x) {
        x.fight();
    }

    static void u(CanSwim x) {
        x.swim();
    }

    static void v(CanFly x) {
        x.fly();
    }

    static void w(ActionCharacter x) {
        x.fight();
    }

    public static void main(String[] args) {
        Hero i = new Hero();
        t(i);
        u(i);
        v(i);
        w(i);
    }
}

interface CanFight {
    void fight();
}

interface CanSwim {
    void swim();
}

interface CanFly {
    void fly();
}

class ActionCharacter {
    // 父类中实现了子类中继承的接口方法
    public void fight() {
    }
}

/**
 * 必须先 extends 然后再 impplements
 */
class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly {
    @Override
    public void fly() {

    }

    @Override
    public void swim() {

    }
}


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Java date conversionNext article:Java date conversion