Thursday, May 3, 2018

Interface Vs Abstract Class

1. In Java you can only extend one class but implement multiple interface. So if you extend a class you lost your chance of extending another class.

2. Interface are used to represent adjective or behavior e.g. RunnableClonableSerializable etc, so if you use an abstract class to represent behavior your class can not be Runnable and Clonable at same time because you can not extend two class in Java but if you use interface your class can have multiple behavior at same time.

3. On time critical application prefer abstract class is slightly faster than interface.

4. If there is a genuine common behavior across the inheritance hierarchy which can be coded better at one place than abstract class is preferred choice. Some time interface and abstract class can work together also where defining function in interface and default functionality on abstract class.


class SmartPhone
  brand: String
  year
  model
 message():abstract
calling():abstract
--------------------------------------------------

inteface Camera
interface Music  
interface AppleWatch

Iphone extends SmartPhone implements Camera, Music, AppleWatch
Android extends SmartPhone implements Camera, Music
windows extends SmartPhone implements Camera, Music

No comments:

Post a Comment