为什么HashMap在扩展AbstractMap时实现Map? [英] Why does HashMap implement Map if it extends AbstractMap?
问题描述
Possible Duplicate:
Java.util.HashMap — why HashMap extends AbstractMap and implement Map?
在java中实现 HashMap< K,V>
我们需要实现 Map< K,V>
。
In java to implement HashMap<K,V>
we need to implement Map<K,V>
.
然而,当我在java类中调试更多时,似乎.... java定义了 HashMap
类,如下所示。
However when I debugged more in java classes it seems that.... java defines HashMap
class as following.
public class HashMap< K,V>
扩展AbstractMap< K,V>
实现Map< K,V>,Cloneable,Serializable
同时,我看到 public抽象类AbstractMap
Map< K,V>
它也实现了接口 Map< K, V>
。
At the same time i saw public abstract class AbstractMap<K,V>
implements Map<K,V>
it also implements the interface Map<K,V>
.
如果抽象类实现了接口,那么实现 Map< K,V> ; at
HashMap
class level?
If abstract class implements the interface then, what is the reason behind implementing Map<K,V>
at HashMap
class level?
根据我的理解 HashMap
类具有从 AbstractMap
继承的所有方法,它们可以被 HashMap
重载为根据要求。
As per my understanding HashMap
class have all the methods inherited from AbstractMap
which can be overridden by HashMap
as per the requirement.
推荐答案
我相信这背后的原因是Java中的抽象类不需要声明/实现接口中的所有方法。
因此
I believe the reasoning behind this is an abstract class in Java need not declare/implement all the methods in the interface. Thus
public interface MyInterface{
void a();
void b();
void c();
}
以下抽象接口的实现是有效的。
the following abstract implementation of the interface is valid.
public abstract class AbstractClass implements MyInterface {
public void a() {}
public void c() {}
public void d() {}
}
因此我相信为了明确大约 HashMap
实现未被抽象类实现的方法,它显示为实现接口 Map
,而它完全是可选的这样做是因为抽象类的任何实现都需要实现抽象类或派生基类中的所有方法。
因此,在上面的示例中,抽象类的有效实现是
Thus I believe in order to be explicit about HashMap
implementing the methods not implemented by the abstract class it is shown to implement the interface Map
whereas it is completely optional to do so because any implementation of the abstract class needs to implement all the methods either in the abstract class or the derived base class..
Thus in the above example a valid implementation to the abstract class is
public class MyClass extends Abstract{
public void a() {}
public void c() {}
public void b() {} //if you dont implement this, compile error
public void d() {}
}
您可以重写如下:
which you can rewrite as follows too:
public class MyClass extends Abstract implements MyInterface {
public void a() {}
public void c() {}
public void b() {}
public void d() {}
}
这篇关于为什么HashMap在扩展AbstractMap时实现Map?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!