Java中的Abstract和Interface的区别

问题

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值