Java 中扩展和实现区别
继承是OOP(面向对象编程)的重要支柱。它是 Java 中允许一个类继承另一个类的特性(字段和方法)的机制。Java 中有两个主要的关键字 extends 和 implements 用于继承。在本文中,将讨论扩展和实现之间的区别。
在进入差异之前,让我们首先了解每个关键字在什么场景中使用。
Extends: 在 Java 中,extends 关键字用于指示正在定义的类是使用继承从基类派生的。所以基本上,extends 关键字用于将父类的功能扩展到子类。在 Java 中,由于歧义,不允许多重继承。因此,一个类只能扩展一个类以避免歧义。
例子:
class One {
    public void methodOne()
    {
        // Some Functionality
    }
}
class Two extends One {
    public static void main(String args[])
    {
        Two t = new Two();
        // Calls the method one
        // of the above class
        t.methodOne();
    }
}
Implements: 在 Java 中, implements 关键字用于实现接口。接口是一种特殊类型的类,它实现了一个完整的抽象并且只包含抽象方法。要访问接口方法,接口必须由另一个类使用 implements 关键字“实现”,并且方法需要在继承接口属性的类中实现。由于接口没有方法的实现,所以一个类可以一次实现任意数量的接口。
// Defining an interface
interface One {
    public void methodOne();
}
// Defining the second interface
interface Two {
    public void methodTwo();
}
// Implementing the two interfaces
class Three implements One, Two {
    public void methodOne()
    {
        // Implementation of the method
    }
    public void methodTwo()
    {
        // Implementation of the method
    }
}
注意:一个接口一次可以扩展任意数量的接口。
例子:
// Defining the interface
interface One {
    // Abstract method
    void methodOne();
}
// Defining a class
class Two {
    // Defining a method
    public void methodTwo()
    {
    }
}
// Class which extends the class Two
// and implements the interface One
class Three extends Two implements One {
    public void methodOne()
    {
        // Implementation of the method
    }
}
下表解释了扩展和接口之间的区别:
| 编号 | 扩展 | 接口 | 
|---|---|---|
| 1 | 通过使用 extends 关键字,一个类可以继承另一个类,或者一个接口可以继承其他接口 | 
通过使用 implements 关键字,一个类可以实现一个接口 | 
| 2 | 继承超类的子类不强制覆盖超类中的所有方法。 | 实现接口的类必须实现该接口的所有方法。 | 
| 3 | 一个类只能扩展一个超类。 | 一个类一次可以实现任意数量的接口 | 
| 4 | 接口可以扩展任意数量的接口。 | 一个接口永远不能实现任何其他接口 | 
极客教程