Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting 0.0 when printing the return value of a method

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading