繁体   English   中英

如何在不同的类Java中访问私有变量

[英]How to access private variable in different class Java

我有一个SpellCheck类,它(以及许多其他东西)从“交互”窗口中给定的文件名创建一个特里。 例如,当我输入java SpellCheck small.txt时,我知道会创建一个词典/词典,因为它是由SpellCheck中的其他方法显示的。

public class SpellCheck{

 // the dictionary

 private LexiconTrie dict;


 // Constructor;  creates window elements

 public SpellCheck(String[] files) {

  dict = new LexiconTrie(files); 

我需要在其他类LexiconTrie中访问该LexiconTrie词典中的信息(迭代,根,节点等)。 但是,每当我尝试访问它时(即使使用SpellCheck.dict时,它也会给我错误“ dict在SpellCheck中具有私有访问权限”(或类似的说法)。

在这种情况下,我是否不完全了解私人/公共阶层的互动? (如果我没有提供足够的信息,请告知我)---------编辑/更新---------------------

这是SpellCheck中的方法

public void doAutoComplete() {
  Collection<String> arr = dict.getCompletions(curText.trim().toLowerCase(), num_value);
  String intro = "Up to " + num_value + " completions";
  display(arr, "No matches found", intro);   
}

我需要在LexiconTrie中编写方法getCompletions getCompletions() 我的教授为我们实现了GUI界面。 该GUI界面创建一个搜索栏,只要用户在搜索栏中键入字母, doAutoComplete就会调用doAutoComplete 在LexiconTrie中,我应该编写getCompletions以返回在LexiconTrie dict (在LexiconTrie dict私下创建和存储)中找到的LexiconTrie dict (“ completions”)。

我在写这些方法时看到了这些:

// Method you have to implement
public Collection<String> getCompletions(String lowerCase, int max) {
  String searchWord = lowerCase;
  int maxReturned = max;
  LinkedList trieMatches = new LinkedList();


  // this is as far as I got, it won't even print the search word. 
 // I get an error from trying to look into dict with .containsWord
  if (dict.containsWord(searchWord)){
    System.out.println(searchWord); 
    //add word/prefix to LinkedList
    //add all children and their children up until max#
  }

  else{
    return null;
  }
}

我需要在其他类LexiconTrie中访问该LexiconTrie词典中的信息(迭代,根,节点等)。

这似乎很奇怪(尽管很难看到更多代码,但是很难告诉)。

通常,您想this进行操作,而不是访问LexiconTrie的另一个实例。

所以代替

void someMethod(SpellCheck spellCheck){
    spellCheck.dict.something();
}

你将会拥有

void someMethod(){
    something();
}
// called from spellcheck as
this.dict.someMethod();

创建用于访问私有变量的方法:

public LexiconTrie getDict(){
  return dict;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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