(Java)将参数从构造函数传递给类的所有方法

(Java)将参数从构造函数传递给类的所有方法,java,class,methods,constructor,Java,Class,Methods,Constructor,假设我在第一课有两种方法。我是否可以将参数传递给class 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 in

假设我在第一课有两种方法。我是否可以将参数传递给class 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));
    }
}

因此,在类测试中,我想从类stuff访问这两个方法,同时传递方法的参数,但我还想传递一个全局类参数(在本例中为5)。我该怎么做?

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

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

前两件重要的事情:

  • 构造函数是用来创建实例的
  • 类名应以大写字母开头
正如你所写:

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);
}

前两件重要的事情:

  • 构造函数是用来创建实例的
  • 类名应以大写字母开头
正如你所写:

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);
}

你已经做了你所描述的。你试过了吗?试一试有什么问题?我建议您为Java类做一些教程。那么您的意思是为变量c提供一个getter方法吗?您已经做了您所描述的。你试过了吗?试一试有什么问题?我建议您为Java类做一些教程。那么您的意思是为变量c提供一个getter方法?