JAVA beginner's question. Why is the result zero?

Asked 2 years ago, Updated 2 years ago, 94 views

package Calc;

import java.util.Scanner;

class Calculator{
    int a,b;
    void setOprands(int a,int b) {
        this.a = a;
        this.b = b;
    }
    int sum() {
        return this.a+this.b;
    }
    void plus() {

    }
    void minus() {
    }
    void run() {
        plus();
        minus();
    }
}
class plus extends Calculator{
    void plus() {
        System.out.println("++"+sum());
    }

}

class minus extends Calculator{
    void minus() {
        System.out.println("--"+sum());
    }
}

public class CalculatorConstructorDemo4 {

    public static void main(String[] args) {
        Calculator Calc = new Calculator();
        Calculator plus1 = new plus();
        Calculator minus1 = new minus();
        Scanner a = new Scanner(System.in);
        Scanner b = new Scanner(System.in);
        //Calc.setOprands(a.nextInt(), b.nextInt());
        Calc.setOprands(10, 20);
        plus1.plus();
        minus1.minus();
    }

}

The question is simple. If you turn the code above

The resulting number appears as 0.

Why can't you calculate the sum method?

inheritance class

2022-09-22 11:02

1 Answers

The calc object and the plus1 object are different.

Because fields a and b were substituted by calling the setOprands method of the calc object, a and b were set only for the calc object.

plus1.setOperands(30, 40);
plus1.plus();
++70

It should be done as above.

One step further, the calculator should be an abstract class, and the plus and minus should also be declared in the abstract method. Of course, you cannot create a Calculator instance. The reason why it should be is that the work of "calculation" is abstract and "plus minus" is concrete.

Study polymorphism, which is the core of object orientation.


2022-09-22 11:02

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.