分组不同类型Java要求的变量

时间:2013-09-04 06:43:47

标签: java

情景是这样的:

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都可以访问。

我该怎么做?

1 个答案:

答案 0 :(得分:3)

这就是接口的用途。

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()./* ... */

您只能访问节点。