Java: 非静态方法 insertValue(int, java.lang.String) 无法从静态上下文中引用

huangapple go评论68阅读模式
英文:

Java: non-static method insertValue(int,java.lang.String) cannot be referenced from a static context

问题

我正在尝试实现一个二叉树,更具体地说,我正在尝试编写将节点插入树中的方法。

一个节点由一个整数键(用于节点的位置)和一个`String`值(节点内部的值)组成。

下面的代码是节点类的代码:

```java
public class Node {
    private int key;
    private String value;
    private Node left;
    private Node right;
    public Node(int key, String value){
        this.key = key;
        this.value = value;
        this.left = null;
        this.right = null;
    }
    public void setLeftChild(Node child) {
        left = child;
    }
    public void setRightChild(Node child) {
        right = child;
    }
    public int getValue() { return key; }
    public Node getLeftChild() { return left; }
    public Node getRightChild() { return right; }
    public int getKey(){ return key; }
}

这是树类:

public class BinaryTree {
    private static Node root;
    public BinaryTree(){
        root = null;
    }
    public BinaryTree(int key, String string) {
        root = new Node(key,string);
    }
    public void insertValue(int key, String value) {
        insert(key, value, root);
    }
    public void insert(int key, String value, Node currentNode) {
        //基本情况
        if (currentNode == null) {
            currentNode = new Node(key, value);
        } else {
            if ( key <= currentNode.getKey())
                insert(key, value, currentNode.getLeftChild());
            else {
                if ( key > currentNode.getKey())
                    insert(key, value, currentNode.getRightChild());
            }
        }
    }
    public static void main(String[] args){
        BinaryTree alpha = new BinaryTree(5,"Bella");
        insertValue();
    }
}

我从Java中得到以下错误:

> Error:(32, 9) java: non-static method insertValue(int,java.lang.String) cannot be referenced from a static context

我不明白为什么。有人能解释一下为什么不起作用吗?这个想法是正确的吗?递归调用是正确的吗?


<details>
<summary>英文:</summary>

I&#39;m trying to realize a binary tree, more specifically I&#39;m trying to write the method to insert a node in the tree.

A node is composed of an integer key (for the positions of the nodes) and a `String` value (the value inside the node).

The code below is for the node class:

public class Node {
private int key;
private String value;
private Node left;
private Node right;
public Node(int key, String value){
this.key = key;
this.value = value;
this.left = null;
this.right = null;
}
public void setLeftChild(Node child) {
left = child;
}
public void setRightChild(Node child) {
right = child;
}
public int getValue() { return key; }
public Node getLeftChild() { return left; }
public Node getRightChild() { return right; }
public int getKey(){ return key; }
}


And this is the tree class:

public class BinaryTree {
private static Node root;
public BinaryTree(){
root = null;
}
public BinaryTree(int key, String string) {
root = new Node(key,string);
}
public void insertValue(int key, String value) {
insert(key, value, root);
}
public void insert(int key, String value, Node currentNode) {
//base case
if (currentNode == null) {
currentNode = new Node(key, value);
} else {
if ( key <= currentNode.getKey())
insert(key, value, currentNode.getLeftChild());
else {
if ( key > currentNode.getKey())
insert(key, value, currentNode.getRightChild());
}
}
}
public static void main(String[] args){
BinaryTree alpha = new BinaryTree(5,"Bella");
insertValue();
}
}


I get the following error from Java:

&gt; Error:(32, 9) java: non-static method insertValue(int,java.lang.String) cannot be referenced from a static context

I don&#39;t understand why. Can someone explain to me why it doesn&#39;t work? The idea is correct? The recursion call is correct?

</details>


# 答案1
**得分**: 1

不要在这行代码中将 `Node root` 声明为 `static`,而应该按照以下方式进行:
```java
private Node root; // 移除 "static" 关键字

并且在 main 方法中还有一个错误:

// insertValue(); // 错误的方式
alpha.insertValue(); // 使用这种方式调用

然后你就没问题了...

现在为什么会发生这种情况

要理解为什么会发生这种情况,你需要理解 Javastatic 的工作原理。使用 static 声明的任何东西,无论是 方法/变量,都会在 的所有对象之间共享。这意味着对于所有对象,变量只会有一个实例,或者可以说所有对象将共享一个单一变量。现在,这样说了,任何 非静态变量/方法 都不能在声明为 static静态方法 的方法中被使用/调用。简单来说,在静态方法中无法使用非静态的变量/方法。因为静态方法属于类的范围,不会传递 this 指针到静态方法中,所以无法使用非静态变量/方法。

如果你理解了静态的概念,现在让我解释一下你的代码中的问题:

第一个问题 - 为什么 static root 是错误的

因为,如果你将 root 声明为 static,那么对于你创建的所有 二叉树,都只会有一个根节点。但是,当然,你希望不同的二叉树有不同的根节点。

第二个问题 - 为什么只调用 insertValue(); 是错误的

你在 main() 方法中,注意到 main()static 的。但是 insertValue() 不是 static 的。但是,你已经知道,你不能从 static 方法中调用 非静态 方法。

希望这能帮助你理解。如果有更多问题,请随时告诉我...

英文:

don't declare Node root as static in this line private static Node root;, rather you should do as follows:

private Node root; // remove the &quot;static&quot; keyword

And you've one more mistake in main method

// insertValue(); // it is wrong
alpha.insertValue(); // call it like this

And you'll be okay...

Now why this happens:

To understand why this happens, you've to understand how static works in java. Anything declared using static, may it be method/variable, is shared between all objects of the class. And that means, there would be only one instance of the variable for all objects or you may say all objects will share one single variable. Now, this said, no non-static variable/method can be used/called in method which is declared is static i.e. static method. Simply, you can't use a non-static variable/method in a static method. Cause, static method belongs to class scope and this pointer is not passed into static method, so you can not use non-static variables/metods.

If you've understood the concept of static, now, let me explain the problems of your code:

First problem - why static root is wrong:

Cause, if you declare root as static there'll be only one root for all Binary Tree you create. But, of course, you'd expect different roots for different binary tree.

Second problem - why just insertValue(); calling is wrong:

You're in main() method, notice that main() is static. But insertValue() is not static. But, you already know, that you can't call a non-static method from a static method.

Hope this clears your understanding. let me know if you've any more questions...

答案2

得分: 0

尝试在主方法中:

alpha.insertValue(1, "Something");

英文:

Try in main method

alpha.insertValue(1,&quot;Something&quot;);

huangapple
  • 本文由 发表于 2020年8月6日 21:19:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/63284511.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定