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

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

问题描述

请用易于理解的语言或某篇文章的链接进行解释。

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

推荐答案

extends 用于扩展类。

implements is 实现接口

接口和常规类之间的区别在于接口中无法实现任何声明的方法。只有实现接口的类才能实现这些方法。接口的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

我建议你对动态绑定,多态性和面向对象编程中的一般继承

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

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