Getting 0.0 when printing the return value of a method

Advertisements
class input{
    private double num1;
    private double num2;
    
    public void setNum1(double num1) {
        this.num1 = num1;
    }

    public double getNum1() {
        return this.num1;
    }
    
    public void setNum2(double num2) {
        this.num2 = num2;
    }

    public double getNum2() {
        return this.num2;
    }
}

class calculator extends input{
    double a = getNum1();
    double b = getNum2();
    
    double add() {
        return a+b;
    }
}

class advcalc extends calculator{
    double less() {
        return a-b;
    }
}

public class Inheritence {
    public static void main(String[] args) {
    advcalc cal = new advcalc();
    cal.setNum1(10);
    cal.setNum2(10);
    
    System.out.println(cal.add());
    }
}

Here I’m practicing inheritance. The first class gets inputs, second class is used for addition and 3rd is used for subtraction. I have created an object of 3rd class. After passing the inputs by setNum1() && setNum1(), when I try to print the return value of the add, it prints 0.0. I couldn’t figure out what’s the issue. Someone help me out please.

>Solution :

a = getNum() is being executed before assigning the value.

double a = getNum1();
double b = getNum2();
double add() {
  return a+b;
}

instead of this you can assign the values inside add method.This way it will be assigned after you create an instance.

double a, b = 0;
double add() {
    this.a = getNum1();
    this.b = getNum2();
    return a + b;
}

There are various ways to achieve this . You can also pass the values in add method or create a parameterized constructor.

Leave a Reply Cancel reply