gpt4 book ai didi

java - 如何将一个类的方法用于另一个类的私有(private)成员对象

转载 作者:行者123 更新时间:2023-12-01 07:04:02 24 4
gpt4 key购买 nike

我正在创建一个类,该类的私有(private)成员之一是另一个类的对象。当我尝试调用已在公共(public)实例方法中创建的类的公共(public)实例方法时,我收到 NullPointerException。

我测试了它,当我从构造函数调用 find 函数时,它工作正常,但是当我从下一个随机函数调用 find 函数时,它给了我异常。发生了什么事?

public class Percolation
{
private WeightedQuickUnionUF uf;
private boolean sites[][];

public Percolation(int N)//constructor
{
sites = new boolean[N][N];
int arraySize = N * N;
WeightedQuickUnionUF uf = new WeightedQuickUnionUF(arraySize);
System.out.println("we found the first node at " + uf.find(31));
}

public void trialQuickFind()
{
System.out.println("we found the first node at " + uf.find(31));
}
}

最佳答案

在构造函数中,您影子 uf。改变

WeightedQuickUnionUF uf = new WeightedQuickUnionUF(arraySize);

this.uf = new WeightedQuickUnionUF(arraySize);

维基百科条目 Variable shadowing说(部分),

In computer programming, variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. At the level of identifiers (names, rather than variables), this is known as name masking. This outer variable is said to be shadowed by the inner variable, while the inner identifier is said to mask the outer identifier.

关于java - 如何将一个类的方法用于另一个类的私有(private)成员对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31258200/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com