与层次继承相关的简单Java程序没有提供所需的输出

时间:2016-12-23 16:46:57

标签: java inheritance

我编写了以下Java程序:

TAB1:

package base;
import java.util.Scanner;

public class Main {

/**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    Scanner obj = new Scanner(System.in);

    System.out.println("Enter first number:  ");
    int num1 = obj.nextInt();
    System.out.println("Enter the second number:  ");
    int num2 = obj.nextInt();

    Add obj1 = new Add();
    Mul obj2 = new Mul();

    obj1.getData(num1, num2);

    int add = obj1.addition();
    int mul = obj2.multiplication();

    System.out.println("The addition of the two numbers is:  " +add);
    System.out.println("The multiplication of the two numbers is:  " +mul);
}

}

TAB2:

package base;

public class Parent {

int num1, num2;

void getData(int x, int y){
    num1 = x;
    num2 = y;
}

}

TAB3:

package base;

public class Add extends Parent {

int addition(){
    int x;
    x = num1 + num2;
    return x;
}
}

TAB4:

package base;

public class Mul extends Parent {

int multiplication(){
    int x;
    x = num1*num2;
    return x;
}
}

当我运行代码时,它会给我一个这样的结果:

Enter first number:
5
Enter second number:
4
The addition of the two numbers is:  9
The multiplication of the two numbers is: 0

我有各种不同输入的相同类型的结果。

乘法的结果总是0

我已多次交叉检查我的代码,但显然我找不到任何错误。

我哪里错了?

非常感谢任何帮助。

3 个答案:

答案 0 :(得分:2)

在调用方法

之前,您应该将参数传递给Mul实例
obj2.getData(num1, num2);
int mul = obj2.multiplication();

答案 1 :(得分:2)

getData()上没有致电obj2

obj2.getData(num1, num2);

答案 2 :(得分:1)

Add obj1 = new Add();
Mul obj2 = new Mul();

obj1.getData(num1, num2);

您创建了两个不同的对象obj1obj2,但只将非零值放入obj1obj2中的值仍为零。