difference between a class and an interface in java code example

Example 1: difference between class and interface in java

A class can be instantiated by 
creating its objects.
An interface is
never instantiated as the methods 
declared inside an interface are abstract
and does not perform any action, 
  so there is no use of instantiating any
interface.
A class is declared using a keyword class. 
In the same way, an interface is 
created using a keyword interface.
The members of a class can have 
access modifier like public, private, protected.
But the members of an interface
are always public as they have to be accessed 
by the classes implementing them.
The methods inside a class are 
  defined to perform an action on the fields
declared in the class. 
The methods inside an interface are purely abstract.
A class can implement any number 
of interfaces but can extend only one 
super class.
An interface can extend any number
of interfaces but cannot implement any
interface.
A class has constructors defined inside
it to get the variable initialized.
But, an interface does not have any
constructors as there are no fields 
to be initialized. The fields of an
interface are initialized 
at the time of their declaration only.

Example 2: difference between interface and abstract class java

Interfaces specify what a class must do. 
It is the blueprint of the class.
It is used to achieve total abstraction. 
We are using implements keyword for interface.

Basic statement we all know in Selenium is
WebDriver driver = new FirefoxDriver();
WebDriver itself is an Interface.
So we are initializing Firefox browser
using Selenium WebDriver.
It means we are creating a reference variable
of the interface and creating an Object.
So WebDriver is an Interface and
FirefoxDriver is a class.

Sometimes we may come across a situation
where we cannot provide implementation to
all the methods in a class. We want to leave the 
implementation to a class that extends it.
  In that case we declare a class
as abstract by using abstract keyword on method
signature.For example in my framework I am using
page object model design pattern and I keep all
locators under Page class. I utilize this locators
in tests but we can't see them in the tests.
Literally we are hiding locators from the test.
Abstraction is methodology of hiding implementation
of internal details and showing the functionality to
users.
Also
1)Abstract classes cannot be instantiated
2)An abstarct classes contains abstract method,
concrete methods or both.
3)Any class which extends abstarct class must
  override all methods of abstract class
4)An abstarct class can contain either
  0 or more abstract method.

Tags:

Misc Example