您的位置:首页 > 编程语言 > Java开发

Java中的Abstract和Interface的区别

2016-03-04 15:00 381 查看
问题

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没有这个限制。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: