Java抽象类实现了一个接口,两者都有相同的方法 [英] Java abstract class implements an interface, both have the same method

查看:215
本文介绍了Java抽象类实现了一个接口,两者都有相同的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在查看一些OOP材料时,我想到了这个让我感到困惑的问题:

While looking at some OOP materials, I thought of this question which confused me a little bit:

考虑使用以下接口,抽象类和具体类:

Consider having the following interface,abstract class, and a concrete class:

package one;

public interface A {

    void doStuff();
}

package one;


public abstract class B implements A {

    public abstract void doStuff();


}

class C extends B{


    public void doStuff() {

    }
 }

Class C 将无法编译除非它提供方法 doStuff()的实现。
这里的问题:

Class C won't compile unless it provides an implementation for method doStuff(). The question here:

1-is doStuff() C <中的方法/ strong>接口 A 的方法的实现,还是类 B 中的抽象方法?更具体一点:JVM
如何处理函数,作为接口或抽象类的调用函数?

1-Is doStuff() method in class C an implementation to the interface A's method, or it is for the abstract method in class B ? to be more specific: How will the JVM treat the function, as an invoked function of the interface or the abstract class ?

2 - 是抽象方法抽象类 B 中的 doStuff()被认为是 doStuff()界面 A 中的方法?因此,强制类 C 实现抽象类的 doStuff()版本而不是接口的?

2-Is the abstract method doStuff() in abstract class B considered to be an "implementation" for the doStuff() method in interface A? so that makes it mandatory for class C to implement the abstract class's version of doStuff() instead of the interface's ?

推荐答案

在界面中,所有方法都是 public abstract

In an interface, all methods are public and abstract.

知道这一点,接口A的doStuff实际上是 public abstract void doStuff()。这应该看起来很熟悉,因为抽象类B具有相同的方法签名。

Knowing this, interface A's doStuff is actually public abstract void doStuff(). Which should look familiar, as Abstract Class B has the same method signature.

要回答问题1,B类的 doStuff()与接口A的 doStuff()相同。由于Java中的所有方法都是虚拟,因此调用 doStuff()都是一样的。

To answer question 1, class B's doStuff() is the same as interface A's doStuff(). Since all methods in Java are virtual, calling doStuff() will be the same regardless of if your C is declared as an A, a B, or a C.

至于问题2,没有。 B的 doStuff()是冗余代码,实际上并没有做任何事情。 C正在实现A的 doStuff(),无论B是否声明 doStuff()

As for question 2, no. B's doStuff() is redundant code that doesn't actually do anything. C is implementing A's doStuff() whether or not B declares doStuff().

这篇关于Java抽象类实现了一个接口,两者都有相同的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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