【问题标题】:(Java) Pass a parameter from a constructor to all the methods of a class(Java) 将参数从构造函数传递给类的所有方法
【发布时间】:2017-10-29 18:36:27
【问题描述】:

假设我在类 1 中有两个方法。我可以将参数传递给类 1 构造函数,然后将参数传递给这两个方法吗?类似于下面的示例代码:

class stuff{
    int c;
    stuff(x){
        c = x;
    }

    public static int sum(int a, int b){
        stuff self = new stuff();
        return c*(a + b);
    }

public static int mult(int a, int b){
    return c*(a*b);
}
}

class test{
    public static void main(String args[]){
    stuff foo = new stuff(5);
    System.out.println(stuff.sum(1, 2));
    System.out.println(stuff.mult(1, 2));
    }
}

所以从类测试中我想从类的东西中访问这两个方法,同时传递方法的参数,但我还想传递一个全局类参数(在这种情况下为 5)。我该怎么做?

【问题讨论】:

  • 你已经按照你的描述做了。你试过了吗?尝试时有什么问题?我建议你为 Java 类做一些教程。
  • 所以你的意思是有一个变量 c 的 getter 方法?

标签: java class methods constructor


【解决方案1】:

前两件重要的事情:

  • 构造函数旨在创建实例。
  • 类名应以大写开头。

如你所愿:

class Stuff{
    int c;
    Stuff(x){
        c = x;
    }
    ...
 }

在这里,您将x 分配给c 字段。
但是sum()mult() 是静态方法。
他们不能使用c 字段。
使这些方法实例化方法,您可以在这些方法中使用c

public static void main(String args[]){
    Stuff foo = new Stuff(5);
    System.out.println(foo.sum(1, 2));
    System.out.println(foo.mult(1, 2));
}

并在这些实例方法中使用当前实例将当前值与传递的参数值相加或相乘:

public int sum(int a, int b){
    return c*(a + b);
}

public int mult(int a, int b){
    return c*(a*b);
}

【讨论】:

    【解决方案2】:

    只需从您的方法中删除 'static' 关键字,不要在 sum 方法中创建新的 'stuff' 实例。相反,只需像现在一样在 test#main 方法中创建东西的实例,它就会像你想要的那样工作。

    【讨论】:

      猜你喜欢
      • 2014-09-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2015-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多