Java中的Abstract和Interface的区别

来源:互联网 发布:淘宝助理批量数据包 编辑:程序博客网 时间:2024/05/01 04:10

问题

I will give you an example first:

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.

I tried my best and Hope this will clear your doubts.

这个问题的就是怎么是使用interface和abstract更好,举了一个例子,如果我们定义一个规范然后不同的实现不同,那么就是interface比较好,如果有一部分公共,给予集成或者实现的类更多选择余地,那么使用abstract比较好。而且接口中只要定义了方法,集成的类就必须完全实现,但是abstract没有这个限制。

0 0
原创粉丝点击