实现与扩展:何时使用?有什么不同? [英] Implements vs extends: When to use? What's the difference?

查看:28
本文介绍了实现与扩展:何时使用?有什么不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请用通俗易懂的语言或文章链接进行解释.

Please explain in an easy to understand language or a link to some article.

推荐答案

extends 用于扩展一个类.

implements 用于实现一个接口

接口和普通类的区别在于,在接口中你不能实现任何声明的方法.只有实现"的类接口可以实现方法.接口的 C++ 等价物将是一个抽象类(不完全相同但几乎相同).

The difference between an interface and a regular class is that in an interface you can not implement any of the declared methods. Only the class that "implements" the interface can implement the methods. The C++ equivalent of an interface would be an abstract class (not EXACTLY the same but pretty much).

此外,java 不支持类的多重继承.这是通过使用多个接口来解决的.

Also java doesn't support multiple inheritance for classes. This is solved by using multiple interfaces.

 public interface ExampleInterface {
    public void doAction();
    public String doThis(int number);
 }

 public class sub implements ExampleInterface {
     public void doAction() {
       //specify what must happen
     }

     public String doThis(int number) {
       //specfiy what must happen
     }
 }

现在扩展一个类

 public class SuperClass {
    public int getNb() {
         //specify what must happen
        return 1;
     }

     public int getNb2() {
         //specify what must happen
        return 2;
     }
 }

 public class SubClass extends SuperClass {
      //you can override the implementation
      @Override
      public int getNb2() {
        return 3;
     }
 }

在这种情况下

  Subclass s = new SubClass();
  s.getNb(); //returns 1
  s.getNb2(); //returns 3

  SuperClass sup = new SuperClass();
  sup.getNb(); //returns 1
  sup.getNb2(); //returns 2

另外,请注意实现接口不需要@Override标签,因为在原始接口方法中没有任何被覆盖

Also, note that an @Override tag is not required for implementing an interface, as there is nothing in the original interface methods to be overridden

我建议你多研究一下面向对象编程中的动态绑定、多态和一般继承

这篇关于实现与扩展:何时使用?有什么不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆