[英]how can we implement methods in multiples classes if we add methods in interface
In an interview interviewer asked this question. 在采访中,面试官问了这个问题。 In an Interface1 there are 10 methods and implementing that Interface1 there are 1000 classes. 在Interface1中有10个方法,实现Interface1有1000个类。 Later in Interface1 I have added 11th method. 后来在Interface1中我添加了第11种方法。 How can you implement that 11th method in all classes. 如何在所有类中实现第11个方法。 later he asked how can you implement in only few classes. 后来他问你怎么能在几节课中实现。 Because of 1000 classes you cannot just go to each class and implement, its time taking. 由于1000个课程,你不能只是去每个班级实施,而是花时间。 Can you tell me how to solve. 你能告诉我怎么解决吗?
He was likely hinting at default
methods in interfaces (available only from java 8
). 他可能暗示接口中的default
方法(仅适用于java 8
)。
Eg: 例如:
interface MyInterface {
default void method() {
// do stuff...
}
}
All classes implementing the interface will inherit the method, you can yet override it in case you need specific behavior. 实现接口的所有类都将继承该方法,您可以在需要特定行为时覆盖它。
class MyClass implements MyInterface {
@Override
public void method() {
// do stuff...
}
}
Also, you can leave the base method blank (that does nothing) and then override it in your 11 classes. 此外,您可以将基本方法留空(无效),然后在11个类中覆盖它。 Or you can have another interface (eg: SubInterface
) extend MyInterface
, override the base method and have your 11 classes implement directly the SubInterface
so they inherit the most specific behavior. 或者您可以使用另一个接口(例如: SubInterface
)扩展MyInterface
,覆盖基本方法并使您的11个类直接实现SubInterface
以便它们继承最具体的行为。 There are countless possibilities for what you have asked (including abstract classes, as someone mentioned in the comments). 你提出的问题有很多可能性(包括抽象类,如评论中提到的那样)。
如果你必须使用以前版本的Java,你可以简单地使用抽象类,它是实现上述场景的一种方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.