[英]How we achieve abstraction in java?
按照定义,抽象隐藏了实现细节,只揭示了功能。 但是,确切地说,我们隐藏了什么,什么地方以及哪一部分?
AFAIK以下程序是Abstraction的示例:
public interface ToBeImplemented {
public string doThis();
}
public class Myclass implements ToBeImplemented {
@override
public string doThis() {
//Implementation
return null;
}
}
如果我错了,这不是抽象,那么正确的抽象例子是什么?
您对抽象的定义是正确的。 您提供的代码绝对是一种抽象形式。
为什么?
因为只向您的代码用户提供接口。 用户只会知道您的代码doThis()
完成了特定任务,但他/她将不知道代码如何完成了特定任务。
例如:
public interface myInterface{
public int sumTo(n);
}
public class myClass implements myInterface{
public int sumTo(int n){
int sum=0;
for(int i=0; i<=n; i++){
sum+=i;
}
return sum;
}
}
在此示例中,用户将仅获得界面,因此他/她仅知道您的代码可总计n 。 但是用户不会知道您使用了for循环求和n 。
在上面的示例中,您可以编写如下内容:
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;
}
}
然后,您可以拥有另一个类和一个主要方法,例如:
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())。
Wikipedia是开始学习的好地方: 抽象(计算机科学)
抽象的本质是保留与给定上下文相关的信息,而忽略与该上下文无关的信息。
约翰·古塔格
将接口与实现分开是提供抽象的一种方法。
Java中的Collections框架就是一个很好的例子。 调用应用程序使用声明为接口的变量(引用)(例如List
或Map
而正在播放的实际对象实际上是一个具体的类,例如ArrayList
或HashMap
。
如果接口提供了所有必需的功能,则调用应用程序无需了解底层实现。
Question中显示的示例代码是一个将接口与实现分开,从而将抽象与实现分开的示例。 如果该示例使用特定的有意义上下文,例如BankAccount
作为接口,并使用SavingsAccount
和CheckingAccount
作为实现,则将大大改善该示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.