【问题标题】:How to access private variable in different class Java如何访问不同类Java中的私有变量
【发布时间】:2014-12-10 02:56:16
【问题描述】:

我有一个类,SpellCheck,它(连同其他各种东西)根据交互窗口中给出的文件名创建一个 trie。例如,当我输入 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 dict(迭代、根、节点等)中的信息。但是,每当我尝试访问它时(即使使用 SpellCheck.dict,它也会给我“dict 在 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()。我的教授为我们实现了一个 GUI 界面。此 GUI 界面创建一个搜索栏,每当用户在搜索栏中键入字母时,该搜索栏就会调用 doAutoComplete。在 LexiconTrie 中,我应该写 getCompletions 以返回在 LexiconTrie dict 中找到的匹配项(“完成”)(这是在 SpellCheck 中私下创建和存储的)。

我看到按照以下思路编写方法:

// 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;
  }
}

【问题讨论】:

  • 好吧,private 字段是私有的。它们不能在课堂外访问。这正是 private 的用途。
  • 我认为你确实不了解 private/public.. private 成员只能在他们自己的类中访问。
  • 在SpellCheck 类中为其提供某种public 访问器/获取器
  • 您需要阅读有关访问修饰符的信息,请查看此内容。 docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
  • 我并没有真正关注你。我猜你应该写LexiconTrie? LexiconTrie 将有自己的私有变量以及私有和公共方法,LexiconTrie 中的方法可以直接访问它们,使用this.field 或通常只是field。您的LexiconTrie 没有理由查看SpellCheck 中的任何内容,甚至不应该知道存在SpellCheck 这样的东西。

标签: java class private


【解决方案1】:

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

这看起来很奇怪(不过,如果不看更多代码就很难说)。

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

所以不是

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

你会的

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

【讨论】:

    【解决方案2】:

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

    public LexiconTrie getDict(){
      return dict;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-03
      • 2012-05-09
      • 1970-01-01
      • 2017-03-04
      • 2020-06-28
      • 2016-03-08
      • 2015-09-25
      相关资源
      最近更新 更多