java继承在一个类中,将变量部署到两个函数中

时间:2015-01-29 11:10:27

标签: java inheritance coding-style

如何使我在此类顶部定义的变量适用于其中的两个函数?

特别是字典和网址。

现在eclipse正在告诉我,关于dict.open(),"标识符在它之后是预期的#34;但是我认为这是一个红色的鲱鱼,因为如果我把它移回{ {1}}方法它将再次起作用。我可以将这些代码复制到这两种方法中,但这种方式非常愚蠢。必须有一种更优雅的方式来实现这一目标。

getHypernyms

2 个答案:

答案 0 :(得分:0)

dict.open();不在任何方法或constructor中,并且每个语句(变量初始化都有一些例外)必须在java中的方法中。

您应该为对象创建一个构造函数,并在其中初始化dict

public class  MITJavaWordNetInterface  {
   //I added private modifier for variables, remove if they're not private
   private String wnhome
   private String path
   private URL url;
   private IDictionary dict;

   //Here is an argumentless constructor:   
   public MITJavaWordNetInterface() { 
       // construct the URL to the Wordnet dictionary directory
       wnhome = System.getenv("WNHOME");
       path = wnhome + File.separator + "dict";
       url = new URL ("file", null , path );
       // construct the dictionary object and open it
      dict = new Dictionary ( url ) ;
      dict.open();
   }
   ///methods
}

答案 1 :(得分:0)

如果您允许MITJavaWordNetInterface个对象,则应创建构造函数并在此处执行初始化:

public class MITJavaWordNetInterface 
{
    String wnhome;
    String path;
    URL url;

    IDictionary dict;

    public MITJavaWordNetInterface() {
        wnhome = System.getenv("WNHOME");
        path = wnhome + File.separator + "dict";
        url = new URL ("file", null, path);
        dict = new Dictionary(url) ;
        dict.open();
    }

    public void getHypernyms(String inut_word) throws IOException {
        ...
    }

    public void getStem(String word) {
        ...
    }
}

public static void main(String[] args) {
    MITJavaWordNetInterface m = new MITJavaWordNetInterface();
    m.getHypernyms(...);
    m.getStem(...);
}

否则,创建一个静态构造函数,在其中进行初始化:

public class MITJavaWordNetInterface 
{
    static String wnhome;
    static String path;
    static URL url;

    static IDictionary dict;

    static {
        wnhome = System.getenv("WNHOME");
        path = wnhome + File.separator + "dict";
        url = new URL ("file", null, path);
        dict = new Dictionary(url) ;
        dict.open();
    }

    public static void getHypernyms(String inut_word) throws IOException {
        ...
    }

    public static void getStem(String word) {
        ...
    }
}

public static void main(String[] args) {
    MITJavaWordNetInterface.getHypernyms(...);
    MITJavaWordNetInterface.getStem(...);
}