java - 我应该如何解释接口(interface)和抽象类之间的区别?

标签 java oop inheritance interface abstract-class

在我的一次采访中,我被要求解释接口(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();
}

现在在每个子类中,我们只需要实现一个方法——依赖于数据库的方法。

关于java - 我应该如何解释接口(interface)和抽象类之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18777989/

相关文章:

java - 我可以使用 extjs 将字段值作为数组提交吗?

python - 无法将对象附加到实例变量(列表)

c# - 如何循环遍历对象列表并在 C# 中搜索字符串

Java,使用foreach循环将修改后的字符串添加到ArrayList

java - 如何使用 Jsoup 从网站获取最后 5 篇文章

java - 可由用户自定义的 Swing 菜单

c# - 不继承 IEnumerable 扩展方法的列表

python - 类变量是可变的吗?

c++ - 尝试与 Base 中的 Derived 函数成为 friend - 为什么它不起作用?

inheritance - Grails继承映射中的鉴别器问题