Java中的Abstract和Interface的区别
2016-03-04 15:00
381 查看
问题
I will give you an example first:
Now suppose you have 3 databases in your application. Then each and every implementation for that database needs to define the above 2 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:
// Each subclass needs to provide their own implementation of this only:
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没有这个限制。
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没有这个限制。
相关文章推荐
- java版本输入一个数,判断这个数值之内所有的素数
- 使用Maven运行Java main的3种方式
- Spring AOP 实例
- java常用的排序算法(冒泡、选择、快速等)
- Java 6.15习题
- Spring Boot + Mybatis + Log4j2开发环境搭建
- Java Web开发入门书籍实例解析(总结一)
- Java中equals和==的区别
- java多线程总结
- Java 单例模式详解
- 浅析 Java Thread.join()
- springmvc的form标签
- Java面向对象基础
- Eclipse MAT插件下载地址
- JAVA设计模式之常见模式-单例模式
- Eclipse快捷键大全
- java得到视频时间
- Java HashMap遍历实践
- Java提高篇—–Java集合细节(三):subList的缺陷
- Java Spring 框架整理