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

voi*_*ila -3 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

}
Run Code Online (Sandbox Code Playgroud)

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

但我想对 Graph 类的变量进行分组,这样

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

我该怎么做?

buc*_*buc 5

这就是接口的用途。

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; }
}
Run Code Online (Sandbox Code Playgroud)

现在,如果您有该类的实例Graph,并且您编写:

Graph graph = new Graph();
graph.getIndex()./* ... */
Run Code Online (Sandbox Code Playgroud)

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

graph.getNode()./* ... */
Run Code Online (Sandbox Code Playgroud)

您只能访问节点。