What are the key differences between Interface
and Abstract class?
If you are
learning Java you might know about what are the key features of java, how can we make
use of basic java concepts, mechanisms like interfaces, abstraction. So, if you
are looking for the key differences between java Interfaces and abstraction
then this is the right place. In this article we will see what are the different
aspects on which we can differentiate java Interfaces and Abstract classes.
· Interface
1.
When we should use –
You can use Interface if you only know the
specification and don’t know how to develop it or you don’t know the
implementation.
Syntax:
interface <interface_name> {
//
declare the fields that are constant
//
declare abstract methods
}
e.g.
interface Emp {
public
abstract getEmpInfo();
public
abstract getSalaryInfo();
}
2.
Multiple Inheritance
By using Interfaces, we can achieve Multiple
inheritance. It means one class can implement one or more interfaces.
3.
Variables
While talking about interface variables,
variables inside the interface are by default public static final.
4.
Variable initialization
You should initialize the variable, whenever
you are writing it inside the interface.
e.g., public static final int i = 20;
5.
Constructor
We can’t create constructor for the interfaces.
As we know all the variables inside the
interface are static, we need a constructor to initialize the variables (non-static
variables). So, in interface we don’t have any non-static variables hence we don’t
need to have constructor for that.
6.
Object
We can not create object of interface.
· Abstract class –
1.
When we should use –
In the case where you know the partial
implementation of class at that time you use the abstract class.
Syntax:
abstract class <class_name> {
//abstract
methods
//non
abstract methods
//data
members
}
e.g.,
abstract class A {
getSalaryInfo(){
System.out.println("Employee Salary Info");
}
public abstract
getEmpInfo();
}
2.
Multiple Inheritance
Abstract class can’t extend more than one class because java
does not support Multiple Inheritance.
3.
Variables
There is no such restriction on how we can
declare the variables. Abstract class variable can be anything, you can make it
public, private etc.
4.
Variable initialization
You may or may not initialize the variables.
e.g.,
public int i = 1;
private int j;
5.
Constructor
We can initialize the non-static variables
whenever we are creating the objects, so we can create the constructor for
abstract class to initialize the variables.
6.
Object
Abstract class does not have any
implementation, it is partially implemented, hence it doesn’t have complete
implementation, since it has partial implementation, we can’t create object of
abstract class.
No comments:
Post a Comment