Question #65155

Change your fraction class so that its instance variables numerator and denominator are hidden (i.e. private). Check that your old client class will not now compile (i.e, if the Fraction class instance variable name ‘numerator’ was used in the client class).

Expert's answer

class Fraction{

private double numerator;

private double denominator;

public double getDecimalValue(){

return numerator/denominator;

}

public double getNumerator() {

return numerator;

}

public void setNumerator(double numerator) {

this.numerator = numerator;

}

public double getDenominator() {

return denominator;

}

public void setDenominator(double denominator) {

this.denominator = denominator;

}

}

class Demo {

public static void main(String[] args) {

Fraction test = new Fraction();

test.numerator = 1; //compilation error

test.denominator = 5; //compilation error

/* works clear*/

test.setNumerator(1);

test.setDenominator(5);

System.out.println(test.getDecimalValue());

}

}

private double numerator;

private double denominator;

public double getDecimalValue(){

return numerator/denominator;

}

public double getNumerator() {

return numerator;

}

public void setNumerator(double numerator) {

this.numerator = numerator;

}

public double getDenominator() {

return denominator;

}

public void setDenominator(double denominator) {

this.denominator = denominator;

}

}

class Demo {

public static void main(String[] args) {

Fraction test = new Fraction();

test.numerator = 1; //compilation error

test.denominator = 5; //compilation error

/* works clear*/

test.setNumerator(1);

test.setDenominator(5);

System.out.println(test.getDecimalValue());

}

}

## Comments

## Leave a comment