是否可以通过继承和接口在一个类中两次存在相同的方法? [英] Can a same method exist in a class twice, through Inheritance and interfaces?

查看:66
本文介绍了是否可以通过继承和接口在一个类中两次存在相同的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是场景:-

class Canine{
  public void roam(){
    System.out.println("Canine-Roam");
  }
}

public interface Pet{    
  public abstract void roam();
}


class Dog extends Canine implements Pet{

  public void roam(){
    System.out.println("Dog Roam");
  }
  public static void main(String [] args){
    Dog adog = new Dog();
    adog.roam();
  }
}

我知道JVM在选择运行哪种方法时一定不要有任何困惑,这意味着哪种方法会被覆盖.但是我还是很困惑.为什么要编译该程序?

I am aware that JVM must not have any confusion in choosing which method to run, that means, which method gets over-ridden. But I am confused anyway. Why does this program compile?

推荐答案

否-同一方法不能在一个类中两次存在.

No - the same method cannot exist in a class twice.

接口仅声明用于类的 requirement 即可实现特定方法.它实际上并没有创建该方法.

An interface simply declares a requirement for a class to implement a particular method. It does not actually create that method.

因此,通过继承获取方法实现的类已定义了该方法.此(单个)实现满足接口的要求.

So a class that acquires a method implemention through inheritance has that method defined. This (single) implementation satisfies the interface's requirements.

在您的情况下:

  1. Dog 扩展了 Canine ,因此这意味着 Canine 中的 roam()方法可用,并且如果不被重写,它将作为Dog对象的一种方法公开.
  2. 但是然后 Dog ,然后使用其自己的 roam()定义来覆盖超类方法.这是允许的,并且在 Dog 上仍然只有一个明确的方法称为 roam()-新的替代方法.
  3. Dog 实现 Pet ,这意味着需要具有 roam()方法.确实如此-这是该接口的有效实现.
  1. Dog extends Canine, so it means that the roam() method from Canine is available, and would be exposed as a method on Dog objects if not overridden.
  2. But then Dog then overrides the superclass' method with its own definition of roam(). This is allowed, and there is still just one unambiguous method called roam() on Dog - the new override.
  3. Dog implements Pet, which means it is required to have a roam() method. It does - so it's a valid implementation of this interface.

这篇关于是否可以通过继承和接口在一个类中两次存在相同的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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