Practical difference between abstract class and interface

Views: 350
Created Date: 29-Sep-2016

Interfaces are rules (Rules because you must give an implementation to them and that you can't ignore or avoid, so that are imposed like rules) which works as a common understanding document among the various teams in software development.

Interfaces give the idea what is to be done but not how it will be done. So implementation completely depends on developer by following the given rules(Means given signature of methods).

Abstract classes may contain abstract declarations, concrete implementations, or both.

Abstract declarations are like rules to be followed and concrete implementations are like guidelines(You can use that as it is or you can ignore it by overriding and giving your own choice implementation to it).

Moreover which methods with same signature may change the behaviour in different context are provided as interface declarations as rules to implement accordingly in different contexts.

 

Example:

 

 

public interface LoginAuth{

   public String encryptPassword(String pass);

   public void checkDBforUser();

}

Now suppose you have 3 databases in your application. Then each and every implementation for that database needs to define the above 2 methods:

 

public class DBMySQL implements LoginAuth{

          // Needs to implement both methods

}

public class DBOracle implements LoginAuth{

          // Needs to implement both methods

}

public class DBAbc implements LoginAuth{

          // Needs to implement both methods

}

But what if encryptPassword() is not database dependent, and it's the same for each class? Then the above would not be a good approach.

 

Instead, consider this approach:

 

public abstract class LoginAuth{

   public String encryptPassword(String pass){

            // Implement the same default behavior here 

            // that is shared by all subclasses.

   }

 

   // Each subclass needs to provide their own implementation of this only:

   public abstract void checkDBforUser();

}

Now in each child class, we only need to implement one method - the method that is database dependent.

 

 

Similar Tags
0.0 0