Sunday 3 February 2019

Interface Class in Apex

Interface is similar to class, it can have methods and variables and methods are default abstract (method with abstract keyword, only declaration not body).

Interface is been used for total abstraction.

Difference between interface and abstract class.


Abstract Class Interface Class
Use abstract keyword to declare abstract class. Use interface keyword to declare interface
An abstract class can be extended using keyword "extends". As interface class can be implemented using keyword "implements".
You can define constructors in abstract class. Interface cannot have any constructors.
Abstract class can have methods with implementations. Interface provides absolute abstraction i.e. methods do not have any implementation or body.
A child/sub-class can only extends one abstract class. A child/sub-class can implements multiple interface
In abstract class, you can call methods in the abstract's child and abstract class methods. In interface all methods are already implemented in child (mandatory), so can directly refer child class.
example:
public abstract class Shape{
public abstract void draw();
}
example:
public interface class Shape{
void shape(string param);
}
You need to use keyword override to implement abstract class method.
public override integer methodName(params..){}
use of keyword override is not required to implement interface class method.
public integer methodName(params..){}

Below is Interface class:
below child class implements the interface

run below code snippet in developer console, you will get an error "type cannot be constructor:Mammal".

Mammal mam = new Mammal();


now run below code and observe the outcome

Human mam = new Human();
system.debug(' ##### => ' + mam.eat('human')) ;

system.debug(' ##### => ' + mam.canfly('human')) ;



Notes:
1. You cannot instantiate interface.
2. An interface does not contains any constructor.
3. All methods declared in interface are abstract.
4. An interface is implemented by class.
5. An interface can extends multiple interface.


Please click on below link for more references: 
Rajat Mahajan, guru99geeksforgeeks, tutorialspoint.com

No comments:

Post a Comment