简体   繁体   中英

How to access instance variable from another class in Java

I am trying to implement a tree data structure. currently I am having an issue programming the addNode() method in GeneralTree.java. I want to do a check to see if the GeneralTree.root() is null, and if so add data to the node. I am having issues accessing the data instance variable from the GeneralNode class in the GeneralTree class.

GeneralNode.java

import java.util.ArrayList;


public class GeneralNode {
    int data;
    GeneralNode parent;
    ArrayList<GeneralNode> children;

    public void setData(int i){
        data = i;
    }

    public int getData(){
        return data;

    }
    }

GeneralTree.Java

import java.util.ArrayList;


public class GeneralTree {

    GeneralNode root;


public GeneralTree(){

}

public void addNode(int data){
    if (GeneralTree.root == null){
        root.setData(data);
    }


}

public boolean isEmpty(){
    return root == null;
}

public GeneralNode root(){
    return root;
}

/*
public int getPosition(){
    return position;
}
*/
public static void main(String[] args){
    GeneralTree myTree = new GeneralTree();
    System.out.println(myTree);
    System.out.println(myTree.root());
    System.out.println(myTree.isEmpty());



}

}

Your addNode method should not compile because root is not static, so you should access it directly, class name is not needed. And the condition should be != null:

public void addNode(int data){
    if (root != null){ //updated line
        root.setData(data);
    }
}

Also, your constructor should initialize root:

public GeneralTree() {
    root = new GeneralNode();
}

You cant reach the root reference like GeneralTree.root if reference is not static. If root's value is same for all GeneralTree object, you declare it as static.

If root's value is not same for all GeneralTree object, change your method like this:

public void addNode(int data){
if (this.root == null){
    root.setData(data);
}

If I'm understanding your question correctly, you need to either create an instance of the GeneralNode or to make the class static.

public static void main(String[] args){

    GeneralTree myTree = new GeneralTree();

    GeneralNode theGeneralNode = new GeneralNode();

    System.out.println(myTree);
    System.out.println(myTree.root());
    System.out.println(myTree.isEmpty());

}

afterwards you can theGeneralNode to reference data in it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM