gpt4 book ai didi

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

转载 作者:bug小助手 更新时间:2023-10-28 01:35:29 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com