在Java中实例化一个对象的多个实例

时间:2016-02-18 05:02:51

标签: java

我正在尝试使用Java编写一个简单的添加程序,我想知道是否可以使对象的多个实例工作:

public class test {
    class Number { 
        public Number(double d, double e) {
    }
    public double number1;
    public double number2;
}

Number numSet1 = new Number(15.0, 30.0);
Number numSet2 = new Number(20.0, 30.0);

private void setNum(double n1, double n2) {
    number1 = n1;
    number2 = n2;
}

private static double getSum(double n1, double n2) {
    return number1 + number2;
}

我希望输出为: 45.0 50.0 分别

不确定我做错了什么。

2 个答案:

答案 0 :(得分:2)

考虑

public class test {
    class Number { 
        public Number(double d, double e) {
          number1 = d;
          number2 = e;
    }
    public double number1;
    public double number2;
}

private void setNum(double n1, double n2) {
    number1 = n1;
    number2 = n2;
}

private double getSum() {
    return number1 + number2;
}

//测试来自main的电话?

Number numSet1 = new Number(15.0, 30.0);
Number numSet2 = new Number(20.0, 30.0);

result = numSet1.getSum ();

答案 1 :(得分:0)

是的,你肯定可以拥有 的多个实例(不是对象,对象就是实例本身)

以下是一个更简单的代码:

public class Addition {
    private double operand1;
    private double operand2;

    public Addition(double o1, double o2) {
        operand1 = o1;
        operand2 = o2;
    }

    public  double getSum() {
        return operand1 + operand2;
    }   

    public static void main(String[] args) {
        double res1 = new Addition(15.0, 30.0).getSum(); // Addition instance 1
        double res2 = new Addition(20.0, 30.0).getSum(); // Addition instance 2

        System.out.println("Result1: " + res1);    // Result1: 45.0
        System.out.println("Result2: " + res2);    // Result2: 50.0
    }

}