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

标签 java abstraction

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

据我所知,以下程序是抽象的示例:

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/

相关文章:

java - 如何在java中的jxdatepicker中设置当前月份和年份(03-2014)作为默认值

c++ - 在实现抽象类的类中定义额外的实现特定函数

design-patterns - 接口(interface)(接口(interface)/抽象类)不是抽象吗?

php - 从 PHP 应用程序中提取数据库的最佳方法是什么?

Java反射: Initialize object using interface but using String value for class name

java - 使用 jxl 修改现有的 excel

java - 当做可能可行的最简单的事情时,在 TDD 或 BDD 中命名方法

java - 如何通过java服务器使用FCM向android设备发送推送通知?

java - Java Web 应用程序中的异常处理

oop - 封装、数据抽象和数据隐藏的精确解释