-4

场景是这样的:

class Graph{
    // Now many variables

    Node masterUser;
    Node masterFilter;
    Node masterLocation;

    Index indexUser;
    Index indexFilter;

    Graph() {
        // INITIALIZE ALL Variables Here
    }
}


// SubClass

class MyClass{

    Graph graph = new Graph();

    // NOW I Can refer all class members of Graph class here by graph Object

}

现在发生的事情是,当我这样做时,graph.所有成员都可以访问。

但我想对类 Graph 的变量进行分组,以便

当用户这样做时graph.Index.,只有所有Index内容都可以访问。当用户这样做时graph.Nodes.,只有所有Node的 s 都可以访问。

我该怎么做?

4

1 回答 1

4

这就是接口的用途。

interface GraphNodes {        
    public Node getMasterUser();
    public Node getMasterFilter();
    public Node getMasterLocation();
}

interface GraphIndexes {
    public Index getIndexUser();
    public Index getIndexFilter();
}

class Graph implements GraphNodes, GraphIndexes {
    private Node masterUser;
    private Node masterFilter;
    private Node masterLocation;
    private Index indexUser;
    private Index indexFilter;

    public GraphNodes getNode() { return this; }
    public GraphIndexes getIndex() { return this; }

    public Node getMasterUser() { return this->masterUser; }
    public Node getMasterFilter() { return this->masterFilter; }
    public Node getMasterLocation() { return this->masterLocation; }
    public Index getIndexUser() { return this->indexUser; }
    public Index getIndexFilter() { return this->indexFilter; }
}

现在,如果你有一个Graph类的实例,你写:

Graph graph = new Graph();
graph.getIndex()./* ... */

您将只能访问索引的 getter 方法,并且如果您键入

graph.getNode()./* ... */

您只能访问节点。

于 2013-09-04T07:40:23.527 回答