面试题答案
一键面试- 默认方法(Java 8 及以上):
- 在接口中给新方法提供默认实现。这样,现有的实现类无需修改代码就可以继续正常工作,因为它们会自动继承接口中默认方法的实现。例如:
public interface MyInterface { void oldMethod(); default void newMethod() { // 默认实现 System.out.println("This is the default implementation of newMethod."); } }
- 实现类如果有需要,可以选择重写这个默认方法来提供自己的实现。
- 抽象类作为中间层:
- 创建一个抽象类实现这个接口,在抽象类中实现新方法的默认行为。
- 现有的实现类继承这个抽象类,而不是直接实现接口。这样,新方法的默认实现就已经在抽象类中提供了,现有实现类无需修改。例如:
public interface MyInterface { void oldMethod(); void newMethod(); } public abstract class MyAbstractClass implements MyInterface { @Override public void newMethod() { // 默认实现 System.out.println("This is the default implementation of newMethod in abstract class."); } } public class MyImplementation extends MyAbstractClass { @Override public void oldMethod() { // 实现旧方法 } }
- 使用适配器模式:
- 创建一个适配器类,实现新接口(包含新方法),并将旧实现类作为成员变量。
- 在适配器类的新方法中,通过调用旧实现类的已有方法来提供新方法的功能,或者提供默认实现。例如:
public interface OldInterface { void oldMethod(); } public class OldImplementation implements OldInterface { @Override public void oldMethod() { // 旧方法实现 } } public interface NewInterface extends OldInterface { void newMethod(); } public class Adapter implements NewInterface { private OldImplementation oldImpl; public Adapter(OldImplementation oldImpl) { this.oldImpl = oldImpl; } @Override public void oldMethod() { oldImpl.oldMethod(); } @Override public void newMethod() { // 通过调用旧方法或提供默认实现 System.out.println("This is the new method implementation in adapter."); } }
- 这样,在需要使用新接口的地方,可以使用适配器类来包装旧实现类,从而实现对新接口的支持,同时不影响旧实现类的原有功能。