7
phuc
7y

What are the biggest differences between abstract class and interface? When to use each?

Comments
  • 5
    1. Interfaces can't implement methods while abstract classes can.
    2. A class can implement a lot of interfaces, but can extend a single class. Interfaces don't "waste" your single inheritance you've got in Java.
  • 3
    what @DeepSpace said and to give you an example I use abstract clases when i want to make a base object for example i want to overwrite the activity class in android so that each activity has a common functionality when is created and also i can put a abstract method there that needs to be implemented in each activity that extands the base object.

    i use the interfaces most of the time for callbacks. in multi thread proramming you don't want to block the flow to wait for a result therefore you call a method from class B that will process smth for you on another thread. you pass within parameters the instance of class A which implements your callback (interface) so the methods defined in interface will be executed when the methods from class b are done and you will get the result expectad in the object's A thread
  • 1
    Point 1 of what @DeepSpace said is no longer accurate. Java interfaces can have implementations as of java 8 (see 'default methods'). Interfaces cannot hide any part of its implementation though; every method is public. Abstract classes may have any visibility on its methods. Abstract classes may also hold state (member variables).

    Standards say you should always build against interfaces. This allows you to decouple your code from any explicit implementation.
Add Comment