Interface vs Abstract Class - Bug Reaper

                  Bug Reaper

Lean about Automation Testing,Selenium WebDriver,RestAssured,Appium,Jenkins,JAVA,API Automation,TestNG,Maven, Rest API, SOAP API,Linux,Maven,Security Testing,Interview Questions

Friday 30 March 2018

Interface vs Abstract Class

Interface

If we know requirement clearly but we are not sure about the implementation then we should go for interface.

Very Important 

Interface is a contract that whosoever implements the interface should implement the abstract method.

Abstract Class
When we have some idea about implementation we should go for abstract class

Every method in interface is always public and abstract that is why it is also know as 100% pure abstract class

public abstract method // this is how function looks like to compiler

so we can't declare here private and protected, final, static

In Interface
Every variable is public, static and final whether we declare or not
but this is not case in abstract class

We can't create object in interface

in interface if we don't initalize the value of the variable , we will get error

public interface FileTest {

int x; // not possible we will get compiler error
}

Here we will get Compile time error:The blank final field x may not have been initialized


In Abstract Class , No error

public abstract class FileTest {

int x; // possible, no compile time error

public void test() {

}
}



We can't use static block in interface








We get compile time error


while in Abstract class we can use static block

Constructors are not there in interface(Reason we don't create object of interface, instead we ask class to implement it, so there is no point of constructor as we don't do  Interface obj=new Interface(); )
You cannot instantiate an interface, which straight away rules out the possibility of having a constructor.

We dont have static methods in Interface because static methods can't be overriden as they are static so whole concept in interface is to override in different classes, who are going to define and use functions of interface




No comments:

Post a Comment