Combining get method with variables inside a secondary get/set method Java

84 views Asked by At

I'd appreciate it if anyone could help. Just what seems like a novice question but I can't figure it out.

I have 3 classes Class1, Class2, UseClass.

In Class1 I have a get/set method (COST is used elsewhere in Class1 but not in those methods)

int class1Num;
final double COST = 120;

public int getNum()
{
    return class1Num;
}
public void setNum(int newNum)
{
    class1Num = newNum;
}

In Class2 I have a final variable and a normal variable and another get/set method.

Class2 extends Class1.

final double FINALNUM = 50;
double totalNum;

public double getTotalNum()
{
    return totalNum;
}
public void setTotalNum(int class1Num)
{
    totalNum = COST * getNum() + FINALNUM;
}

public void display()
{
    System.out.println("Final Number: " + getTotalNum() );
}

Basically what I need to do is I need to in Class2. First multiply COST by the getNum() method from Class1 and then add FINALNUM to that total. This is just my recent attempt but I've tried adding FINALNUM in the system.out to no avail (although multiplication works fine for some reason).

display() is called in the UseClass to output the final result.

I have no other ideas and not exactly sure what I'm looking for when searching online so I figured asking here may help

Any help would be great

Thanks.

1

There are 1 answers

0
PandaHsien On

According to your statements, the classes are following I guess:

public class Class1 {
    int class1Num;
    final double COST = 120;

    public int getNum()
    {
         return class1Num;
    }

    public void setNum(int newNum)
    {
         class1Num = newNum;
    }
}

public class Class2 extends Class1{
    final double FINALNUM = 50;
    double totalNum;

    public double getTotalNum()
    {
        return totalNum;
    }

    public void setTotalNum(int class1Num)
    {
        // Note: need assign field member "class1Num" inherited from Class1.
        // Otherwise, it will be zero and cause incorrect value of getNum()
        totalNum = COST * getNum() + FINALNUM;
    }

    public void display()
    {
        System.out.println("Final Number: " + getTotalNum() );
    }
}

The problem is that "setTotalNum(int class1Num)" doesn't assign class1Num which inherited from Class1. You can call "setNum(class1Num);" before" totalNum = COST * getNum() + FINALNUM;"

public class Class2 {
    ...
    public void setTotalNum(int class1Num) {
        setNum(class1Num);
        totalNum = COST * getNum() + FINALNUM;
    }
    ....
}