简体   繁体   中英

abstract class MouseAdapter vs. interface

I noted this (it's a java.awt.event class).

public abstract class MouseAdapter implements MouseListener, 
                                              MouseWheelListener, 
                                              MouseMotionListener {
....
}

Then you are clearly forced to extend from this adapter

public class MouseAdapterImpl extends MouseAdapter {}

the class is abstract and implements no methods. Is this a strategy to combine different interfaces into a single "basically interface" ? I assume in java it's not possible to combine different interfaces into a single one without using this approach.

In other words, it's not possible to do something like this in java

public interface MouseAdapterIface extends MouseListener, 
                                           MouseWheelListener, 
                                           MouseMotionListener {
}

and then eventually

public class MouseAdapterImpl implements MouseAdapterIface {}

Is my understanding of the point correct ? what about C# ?

In other words, it's not possible to do something like this in java

public interface MouseAdapterIface extends MouseListener, 
                                           MouseWheelListener, 
                                           MouseMotionListener {
}

Sure, you can do that in Java.

The reason for having an abstract class is that it also provides default implementations for all methods (which do nothing), so that you only have to implement those you are interested in.

the class is abstract and implements no methods

Not true. It is abstract, but it does implement all methods in the three interfaces.

In Dotnet, you can inherit your interface from n other interfaces but not from any abstract class. If MouseListener,MouseWheelListener,MouseMotionListener are interfaces then dotnet allows to inherit from it.

This is not allowed in DotNet


public abstract class AbstractA
{
  public abstract void A();
}

public interface IA:AbstractA
{
  void A();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM