2
ahtolba
17d

So it's a basics question I know, but is the main difference between abstract classes and interfaces is just that you can use non-abstract methods in abstract classes but not in interfaces ??

Comments
  • 1
    you can use non-abstract methods in interfaces too :) Since java7 I think. But it's rarely a good idea to do that.

    Interfaces are there do define a type of the class/object and define what it can do.
    Abstract classes on top of that define some default behaviour

    Interfaces: all the contents are static.
    Abstract classes: not necessarily (i.e. you can have instance-speciffic state)

    In Java you can implement multiple interfaces, but you can only extend one class.

    Interfaces can be proxied and loaded dynamically w/ ServiceLoader easily. It's not the case for Abstract classes.

    Usually abstract classes are used when you have the base behaviour defined in your class but you still need a few things for that clockwork to run. It's an "almost working mechanism". Derivates of an abstract class supply those missing implementation-speciffic properties/implementations.

    Interfaces are usually used to define an abstract set of properties of the class: type, methods' signatures. That's all.
  • 1
    Wow, thanks man 😃
  • 1
    @ahtolba Think of it this way (if you are familiar with SOAP):

    interface is a WSDL file

    abstract class is a set of stubs generated from that wsdl file: they know what structures to send, what responses to receive, how to map/process them, but they still require you to implement a few methods, like getConnection() or so.
Add Comment