我们如何在 java 中实现抽象?

How we achieve abstraction in java?

根据定义,抽象是隐藏实现细节并仅揭示功能。但是,我们究竟在隐藏什么、隐藏在哪里、隐藏哪一部分?

AFAIK 以下程序是抽象的示例:

public interface ToBeImplemented { 

   public string doThis();
}

public class Myclass implements ToBeImplemented {

@override
public string doThis() {

//Implementation

 return null;
 }
}

如果我错了,这不是抽象,那么正确的抽象示例是什么?

您对抽象的定义是正确的。您提供的代码绝对是一种抽象形式。

为什么?

因为你的代码的用户只会被提供接口。用户只会知道您的代码 doThis() 完成了某项任务,但 he/she 不知道代码如何完成该任务。

例如:

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;
 }
}

在这个例子中,用户只会得到接口,所以he/she只知道你的代码可以加起来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,和一个主要方法,例如:

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())。

维基百科是开始学习的好地方:Abstraction (computer science)

The essence of abstractions is preserving information that is relevant in a given context, and forgetting information that is irrelevant in that context.

John V. Guttag

将接口与实现分离是一种提供抽象的方式。

Collections framework in Java is an excellent example. Calling apps work with variables (references) declared as the interface such as List or Map while the actual object in play is really a concrete class such as ArrayList or HashMap.

如果接口提供了所有需要的功能,则调用应用程序无需了解底层实现。

问题中显示的示例代码是将接口与实现分离的示例,因此也是抽象的示例。如果该示例使用特定的有意义的上下文(例如 BankAccount 作为接口,并使用 SavingsAccountCheckingAccount 作为实现,那么该示例将会得到很大改进。