在我的一次采访中,我被要求解释接口(interface)和抽象类之间的区别。
这是我的回应:
Methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behaviour.
Variables declared in a Java interface are by default final. An abstract class may contain non-final variables.
Members of a Java interface are public by default. A Java abstract class can have the usual flavours of class members like private, protected, etc.
A Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”.
An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
A Java class can implement multiple interfaces but it can extend only one abstract class.
但是面试官不满意,告诉我这个描述代表“书本知识”。
他要求我给出更实际的答复,并解释何时我会选择一个抽象类而不是接口(interface),并使用实际示例。
我哪里做错了?
我先给你举个例子:
public interface LoginAuth{
public String encryptPassword(String pass);
public void checkDBforUser();
}
假设您的应用程序中有 3 个数据库。然后该数据库的每个实现都需要定义上述两种方法:
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
}
但是如果 encryptPassword()
不依赖于数据库,并且每个类都相同,该怎么办?那么上述方法就不是一个好方法了。
请考虑以下方法:
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();
}
现在在每个子类中,我们只需要实现一个方法——依赖于数据库的方法。
我是一名优秀的程序员,十分优秀!