Java静态引用与动态引用和调用

时间:2015-06-25 12:05:44

标签: java static public

在这里,我将发布我的代码的两个简化版本(但这是自给自足的,你不需要知道其他变量是什么等等。)

我需要包含我的问题的类从另一个包导入我的类Synchronous_Writing。我需要这个类是静态的,因为各个类必须调用它并随后修改创建的对象, 并且它实际上不是将数据从一个类传递到另一个类的选项,因为这会使代码真的不可读......

此类是公开的,但仍然从当前类访问涉及下面版本下面描述的一些问题。 谢谢你的帮助。

Synchronous_Writing的主干:

public final Synchronous_Writing {

     public Synchronous_Writing() {
     // variable to initialize
     }
     public static void writer ()
     {
     //operation to be performed
     }
 }

第一版:

import Synchronous_Writing;

public classFileToEdit_Parser {
  // A public static final class
  Synchronous_Writing SyncedWriter ; // note to an editor; this is a ";", not a {

  public FileToEdit_Parser  (
    String inputFile_FileToEdit, 
    String outputFile_EditedFile, 
    Charset charset, 
    String HitList_fieldsSeparator, 
    String CommentLine) 
    throws IOException, FileNotFoundException
  {
      SyncedWriter = new Synchronous_Writing(
      outputFile_EditedFile, charset, StandardOpenOption.APPEND);
  }

  protected void parser_writer(Path FileToEdit) 
    throws IOException, FileNotFoundException 
  {
    SyncedWriter.writer();
  }
}

//这里的问题是编译器说"来自类型Synchronous_Writing的静态方法writer(String)应该以静态方式访问" (逻辑,因为Synchronous_Writing是静态的)

第二版:

import Synchronous_Writing;
// A public static final class
public classFileToEdit_Parser
{
  public FileToEdit_Parser (
    String inputFile_FileToEdit, 
    String outputFile_EditedFile, 
    Charset charset, 
    String HitList_fieldsSeparator, 
    String CommentLine) throws IOException, FileNotFoundException
  {
    SyncedWriter = new Synchronous_Writing(
      outputFile_EditedFile, charset, StandardOpenOption.APPEND);
  }

  protected void parser_writer(Path FileToEdit) 
    throws IOException, FileNotFoundException 
  {
  // SyncedWriter.writer () 
  // won't work, I don't really understand why since 
  // the constructor is public, but I still can't access it

  Synchronous_Writing.writer () 
  // will work, but the compiler keeps saying that SyncedWriter
  // variable is not used (which is quite true, since only the
  // constructor is initialized)
  }
}

为了纠正第一个版本的问题,我因此压制了Synchronous_Writing SyncedWriter;在类声明中并通过类而不是对象切换到变量调用。抑制Synchronous_Writing SyncedWriter;不是强制性的,但它并没有改变问题。

我的第二个问题是SyncedWriter.writer()没有工作,我真的不明白为什么因为构造函数是公开的,但我仍然无法访问它。 Synchronous_Writing.writer()可以工作,但是编译器一直说不使用SyncedWriter变量(这是真的,因为只初始化了构造函数)

最后,这两个代码都以某种方式破坏了,我想知道它是正确的,所以请随时提供你的见解。

2 个答案:

答案 0 :(得分:1)

java中的

static表示方法不知道除传递参数和其他静态变量之外的任何上下文。

您正尝试在Synchronous_Writing中创建上下文,而不是在此上下文中调用静态方法。 调用方法而没有在Synchronous_Writing中初始化上下文的步骤可能会出现异常。 这是一种不好的做法,而不是自我解释的代码。

如果您需要静态方法,请确保它不依赖于需要初始化的任何上下文。

答案 1 :(得分:1)

通常,当您想要从多个其他类修改类的实例(对象)时,请使用Singleton设计模式。你只需要一个静态的吸气剂,你的所有问题都将得到解决。谷歌Singleton design pattern java example,并确信它的真棒和适用性!