【问题标题】:Private access? Java [closed]私人访问? Java [关闭]
【发布时间】:2012-07-26 08:11:21
【问题描述】:

我有一个与变量“totalFloat”有关的私人访问错误。但是,我一直在引用和使用同一个类的方法,没有这个问题。

在这种情况下,是否有解决私人访问错误的通用方法?

public static void writeHtmlFile() {
  double contentsChangeDraw;

  String ChangeDrawer = "ChangeFloat.html";
  try {
    PrintWriter outputStream = new PrintWriter(ChangeDrawer); 
    contentsChangeDraw=cd.getTotalFloat(totalFloat); 

    // totalFloat has private access in ChangeDrawer, which means I am
    // unable to use the method to calculate the array that needs to be written  

    outputStream.println(contentsChangeDraw); 
    outputStream.close(); 
    System.out.println("The contents of the ChangeDrawer have been written to a file");
  } catch (FileNotFoundException e) {
    e.printStackTrace();      
  }       
}

【问题讨论】:

  • 是 totalFloat 非静态
  • 什么是光盘?它是 ChangeDrawer 类型的对象吗?
  • 我们需要更多的上下文。我们不知道这个方法属于哪个类。我们不知道 totalFloat 是如何以及在哪里定义的。我们不知道您收到的确切错误消息。
  • 除非您正在为 android 编程,否则最好将其保留为私有并为其创建一个 getter 方法。
  • @GenericJon 为什么要为 android 编程改变好/坏实践的定义? ;)

标签: java class private


【解决方案1】:

我敢打赌totalFloat 有这样的声明:

private int totalFloat; // or double, or boolean, or something else

您不能从静态方法访问它,因为它是一个成员变量。实现它

private static int totalFloat; // or double, or boolean, or something else

访问它(或将您的方法 writeHtmlFile() 更改为非静态)。

【讨论】:

    猜你喜欢
    • 2010-10-15
    • 2019-08-28
    • 2012-09-30
    • 1970-01-01
    • 2014-08-21
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多