0

关于 JavaFX 类的新手 Q。Main 是 JavaFX 中的一个主要的起始类,它没有构造函数(我不知道为什么)

主.java

class Main extends Application {
   Log  log;   // class, not shown here
   Work work;
   @Override
   public void start() // entry point
   {
      log  = new Log("main.log"); // opens log file, need to be non-static
      work = new Work();
   }
}

工作.java

class Work{
     public Work() // constructor
    {
       Main.log.write("Making work object");  // error
       // What is the right method to call one non-static class from another ???
    }
4

3 回答 3

1

将日志传递给 Work 实例。

class Main extends Application {
   Log  log;   // class, not shown here
   Work work;
   public start() // entry point
   {
      log  = new Log("main.log"); // opens log file, need to be non-static
      work = new Work(log);
   }
}

== Work.java ==

class Work{
    Log  log;
    public Work(Log log) // constructor
    {
       this.log = log;
       log.write("Making work object");           
    }
于 2013-11-07T12:51:37.593 回答
1

尝试这个

class Main extends Application {
   public static Log  log = new Log("main.log");   // class, not shown here
   Work work;
   public start() // entry point
   {
       work = new Work();
   }
}

那么只有你可以使用

Main.log.write("Making work object");
于 2013-11-07T12:55:16.750 回答
0

你的Log需要是publicstatic

只有当某些东西被声明public时,你才能在另一个类中访问它(我的意思是没有继承)

只有当某事被声明static时,你才能将其称为Classname.VariableName

class Main extends Application {
   public static Log  log; // see the change ?   
   ...
   public void start() // this needed a return type
   {
      ...
   }
}
于 2013-11-07T12:47:25.067 回答