Interface, Abstract and Inheritance
1. Interface: It is the blueprint for the class what to do. It is a skeleton for class.
2. This blueprint helps all programmers to know what the layout of functionality is.
3. All methods, variables are declared there in interface.
4. There are no definitions because definition part is taken care by classes.
5. The default methods are public abstract in interface.
6. Variable by default are public static “Final” in interface.
7. Can no instantiate – no definitions so nothing can be achieved.
8. Interface supports multiple inheritances… It can implement more than interface at a time.
Multiple interfaces at a time by a single class.
Extens versus Interface
Abstract class: It is also a blueprint having common code for the classes to follow. But there is a
difference between interface and abstract:
Feature Abstract Class Interface
Used to share common code (partial Used to define a contract/blueprint only
Purpose
implementation)
Can have both abstract and concrete Can only have abstract methods (until
Methods methods. can have Static, Final, private Java 8+) now static methods allowed
metds
All variables are public static final
Variables Can have instance variables (non-final) (constants)
Cannot have constructors
Constructors Can have constructors
A class can implement multiple
Multiple
A class can extend only one abstract class interfaces
Inheritance
All methods are public abstract (by
Access
Can be public, protected, private default)
Modifiers
When you want to share code + force When you want to force
When to Use
some methods to be implemented implementation but not share code
1. We cannot create an object directly of abstract class or interface directly – though we
can create a reference and use in subclass.
2. abstract class can implement one or more interfaces
3. An interface can extend one or more interface
4. abstract class can extend another abstract class
5. A class cannot extend multiple abstract classes.
6. Interface methods can be static or default. Static methods cannot be overridden by
implementing classes. Default methods may have a definition and can be overridden.
Interface A
Extends
Interface B
Implements (Abstract Class C Implements B)
Abstract Class C
Class D extends C
Class D Implements Interface B
Class D