Passing Object Through Method in Java

53 Views Asked by At

I am trying to get a second object to pass through my method so that I can add values from each object. I am trying to access the numerator attribute and denominator attribute from the "secondRational" object.

@Override
public RationalInterface add(RationalInterface secondRational) {
    // How do I access the secondRational values within the child class Rational?
    int numerator = this.num * secondRational.den + this.den * secondRational.num;
    int denominator = this.den * secondRational.den;
    this.num = numerator;
    this.den = denominator;
    return this;
} // end add

The error that I receive is that the den symbol for secondRational is not resolved.

enter image description here

1

There are 1 best solutions below

1
Manuna Mady On

To access the numerator and denominator attributes from the secondRational object, you need to use the dot notation. For example, to access the numerator attribute, you would use the following code:

int numerator = secondRational.numerator; To access the denominator attribute, you would use the following code:

int denominator = secondRational.denominator; You can then use these variables in your code to perform the addition operation.

Here is an updated version of your code that uses the dot notation to access the secondRational values:

@Override
public RationalInterface add(RationalInterface secondRational) {

    // Access the numerator and denominator values from the secondRational object
    int numerator = this.num * secondRational.denominator + this.den * secondRational.numerator;
    int denominator = this.den * secondRational.denominator;

    // Update the numerator and denominator values for the current object
    this.num = numerator;
    this.den = denominator;

    // Return the current object
    return this;
} // end add