Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do many Collection classes in Java extend the abstract class and implement the interface as well?

Why do many Collection classes in Java extend the Abstract class and also implement the interface (which is also implemented by the given abstract class)?

For example, class HashSet extends AbstractSet and also implements Set, but AbstractSet already implements Set.

like image 929
JRomio Avatar asked Oct 04 '10 11:10

JRomio


People also ask

Can a class extend an abstract class and implement an interface?

Remember, a Java class can only have 1 superclass, but it can implement multiple interfaces. Thus, if a class already has a different superclass, it can implement an interface, but it cannot extend another abstract class. Therefore interfaces are a more flexible mechanism for exposing a common interface.

Why would an abstract class implement an interface?

If abstract class doesn't have any method implementation, its better to use interface because java doesn't support multiple class inheritance. The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class.

Why are abstract classes and interfaces both needed in Java?

An abstract class is used if you want to provide a common, implemented functionality among all the implementations of the component. Abstract classes will allow you to partially implement your class, whereas interfaces would have no implementation for any members whatsoever.

What is the advantage of abstract class over interface in Java?

In Java, abstract classes give the ability to define both concrete and abstract methods whereas interfaces only give the ability to implement abstract methods.


1 Answers

It's a way to remember that this class really implements that interface.
It won't have any bad effect and it can help to understand the code without going through the complete hierarchy of the given class.

like image 77
Colin Hebert Avatar answered Oct 05 '22 19:10

Colin Hebert