【问题标题】:Getting parameter for a method from a method that didn't call it从没有调用它的方法获取方法的参数
【发布时间】:2014-04-27 01:51:35
【问题描述】:

想知道我将如何解决这个问题,希望标题有意义。

如果没有,这里有一个例子:

var1 在 main 方法中
main方法调用method1
method1调用method2
method2调用method3
method3调用method4
method4调用method5
method5 想要用户 var1

显然,它在层次结构的深处。所以让每个方法调用 var1 对我来说似乎很愚蠢。

有没有办法让method5从main方法调用var1?

【问题讨论】:

    标签: java methods


    【解决方案1】:

    如果所有方法都在同一个类中,您可以通过在类的开头声明它来使其成为类级变量。您可以将其设为 static,以便该类的任何实例都可以访问相同的数据,或者在没有 static 修饰符的情况下为每个实例设置一个单独的值。

    // static variable shared across all instances
    private static Type variable;
    // static public is accessible to all classes
    public static Type variable;
    // access with YourClasss.variable
    // or only available internally
    private Type variable;
    

    或者,您可以通过将变量声明为 public 或通过公共 getter 方法直接授予对变量的公共访问权限。

    // accessible by any class
    public Type variable;
    // controlled access through a getter
    private Type variable;
    public Type getVariable() {
        return variable;
    }
    

    你应该阅读Java's variable modifiers

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-10
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 2018-05-16
      • 2014-02-13
      • 1970-01-01
      相关资源
      最近更新 更多