简体   繁体   中英

Cannot access private members of same type in Java

I am unable to access private members of same type in Java. I am creating a method 'add' on the Fraction type but I cannot access the other fractions private vars to compare.

public Fraction add(Fraction f) {
    int add1 = (this.numerator*f.denominator)+(this.denominator*f.numerator);
    int add2 = this.denominator*f.denominator;
    return createFraction(add1,add2);
}

Should I be using some sort of reflection feature to achieve this?

Extra info: I have not declared the private members on the interface.

Extra info: I am not permitted to use getters and setters on this class

Extra info: I am not permitted to make those fields public

You should create getters and setters on your Fraction class so you can get the values of the private variables as well as set them.

public class Fraction{
   private int numerator;
   private int denominator;
   public Fraction(final int numerator, final int denominator){
     this.numerator = numerator;
     this.denominator = denominator;
   }
   public int getNumerator(){
     return this.numerator;
   }
   public int getDenominator(){
     return this.denominator;
   }
   public void setNumerator(final int numerator){
    this.numerator = numerator;
   }
   public void setDenominator(final int denominator){
    this.denominator = denominator;
   }
}

You can then change your code to this:

public Fraction add(Fraction f) {
    int add1 = (this.numerator*f.getDenominator())+(this.denominator*f.getNumerator());
    int add2 = this.denominator*f.getDenominator();
    return createFraction(add1,add2); //createFraction can be simply new Fraction(add1, add2);
}

You could use Reflection to get the value of the field by using Field.setAccessible , but it is much easier and cleaner to write a getter for the field.

Example Usage:

Field field = f.getClass().getDeclaredField("numerator"); 
f.setAccessible(true);
int numerator = (int) field.get(f);

Your code could then be changed to:

public Fraction add(Fraction f) throws NoSuchFieldException, IllegalAccessException{
    Field fieldNumerator = f.getClass().getDeclaredField("numerator");
    fieldNumerator.setAccessible(true);
    Field fieldDenominator = f.getClass().getDeclaredField("denominator");
    fieldDenominator.setAccessible(true);
    final int numerator = (int) fieldNumerator.get(f);
    final int denominator = (int) fieldDenominator.get(f);
    int add1 = (this.numerator*denominator)+(this.denominator*numerator);
    int add2 = this.denominator*denominator;
    return createFraction(add1,add2); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM