根据定义,抽象是隐藏实现细节并仅揭示功能。但究竟是什么,我们藏在哪里,藏在哪一部分?
据我所知,以下程序是抽象的示例:
public interface ToBeImplemented {
public string doThis();
}
public class Myclass implements ToBeImplemented {
@override
public string doThis() {
//Implementation
return null;
}
}
如果我错了,这不是抽象,那么正确的抽象示例是什么?
最佳答案
在上面的例子中你可以这样写:
public interface ToBeImplemented {
public string doThis();
}
public class ImplementationA implements ToBeImplemented {
@override
public string doThis() {
//ImplementationA of doThis
return null;
}
}
public class ImplementationB implements ToBeImplemented {
@override
public string doThis() {
//ImplementationB of doThis
return null;
}
然后你可以有另一个类,例如一个main方法:
class SomeClass{
public static void main(String[] args) {
ToBeImplemented someImplementation;
//now you can pick an implementation, based on user input for example
if (userInput == something)
someImplementation = new ImplementationA();
else
someImplementation = new ImplementationB();
//do some staff
//Regardless of the user input, main method only knows about the
//abstract "ToBeImplemented", and so calls the .doThis() method of it
//and the right method gets called based on the user input.
someImplementaion.doThis();
//at That
}
}
抽象是您可以声明一个 ToBeImplemented 引用,然后将其分配给 ImplementationA 或 ImplementationB(以及可能的任何其他实现)。但是您针对抽象的 ToBeImplemented 编写代码,并让一些条件决定应该调用什么 ToBeImplemented 的正确实现(以及作为结果的 doThis())。
关于java - 我们如何在java中实现抽象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33985141/