JAVA - 抽象 [英] JAVA - Abstraction

查看:29
本文介绍了JAVA - 抽象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Java 中的抽象有点困惑.

I am little confused about abstraction in java.

我检查了很多页面,说明抽象是数据隐藏(隐藏实现).

I have checked many pages stating that abstraction is data hiding(Hiding the implementation).

我对抽象的理解是部分实现".只需在抽象类/接口中定义您将需要的内容,然后扩展/实现它们并添加您自己的功能即可.

What I understand about abstraction is it is 'partial implementation'. Just define what you are going to need in an abstract class/interface and afterwards extend/implement them and add your own functionality.

我不明白的是这是如何隐藏数据的?实现类/接口后,您将可以访问代码,并根据需要对其进行修改.

What I don't understand is how this is a data hiding? You are going to get access to the code once you implement the class/interface and you will modify it according to your need.

我已经检查了很多关于此的问题和文章,但仍然对此感到困惑.

I have checked many questions, articles on this but still confused about this.

感谢任何帮助.谢谢.

推荐答案

也许一个例子能更好地帮助你.假设您要实现一个 Graph 类,该类可能具有邻接列表或邻接矩阵来表示其节点.所以抽象地说,你至少要在这个图中addNode"addEdge":

Maybe an example help you better. Suppose you want to implement a Graph class which may be have adjacency list or adjacency matrix to represent its nodes. So in abstract you want to "addNode" "addEdge" to this graph at least:

public abstract class Graph
{
    public abstract int addNode();
    public abstract void addEdge(int from, int to);
}

现在你可以扩展两个类:

Now you can extend two classes:

public class GraphAdjList extends Graph
{
    private Map<Integer,ArrayList<Integer>> adjListsMap;
    public int addNode()
    {
        //list based implementation 
    }
    public void addEdge(int from, int to)
    {
        //list based implementation
    }
}

public class GraphAdjMatrix extends Graph
{
    private int[][] adjMatrix;
    public int addNode()
    {
        //matrix based implementation 
    }
    public void addEdge(int from, int to)
    {
        //matrix based implementation
    }
}

当您从这两个类中调用 addEdge 中的任何一个时,您不必担心其背后的数据结构,您只知道获得了所需的结果,例如:

when you call either of addEdge from these two classes you don't have to worry about the data structure behind it, you just know that you get the result you needed so for example:

Graph g1,g2;
g1 = new GraphAdjList();
g2 = new GraphAdjMatrix();

g1.addEdge(1,2);
g2.addEdge(1,2);

通过多态,您可以调用两个不同的函数,但得到的结果与图的客户端相同.

through polymorphism you call two different functions but get the same result as client of the Graph.

另一个现实生活中的例子是汽车刹车.作为汽车客户,制造商在不知道后端刹车的实现方式的情况下给了你一个踏板.它可以是后部的鼓式制动器或盘式制动器.你只需要踩刹车!

Another real life example would be car brakes. As a car client, the manufacturer gives you a pedal to push without knowing what is the implementation of the brake in the back-end. It can be a drum-brake or disc-brake implementation in the back. All you need is to push the brake!

这篇关于JAVA - 抽象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆