Creating instance variables

Instance variables of an object act as data containers within an object. The entire object state is present within the instance variables.
Each object has its own copy of the instance variables

  1. Create a private instance variable of type integer with the name "numerator" and initialize to one
  2. Create a private instance variable of type integer with the name "denominator" and initialize to one
The "numerator" and "denominator" variables hold the numeric values for the Fraction object.
The visbility modifier being private denotes that only Fraction Object's methods have access to instance variables.
The instance variables cannot be accessed outside the Fraction Object
Since no other object can access the internal representation of the fraction object, the internal represenation can be changed in the future.

Creating Constructor

Constructor is invoked when a new object is created. The code to initialize the object is present within the constructor.

  1. Create a public constructor taking two parameters with the first parameter being the numerator and the second parameter being the denominator.
    The fraction object is always initialized with the numerator and denominator it represents.
  2. Assign the parameters numerator and denominator to the corresponding instance variables
    The keyword "this" when used within an object is the reference to the calling/host object
    If you consider the following example the parameters passed into the constructor have the same name as the instance variables eg: numerator
    So when name "numerator" is used within the constructor, the parameter passed to the constructor is referred. In this case to refer to an instance variable of the current object, "this" keyword is used.
Make a note that one more check here could have been if the denominator is zero.

Creating Accessors

  1. Create a getNumerator method with the following signature
    Name: getNumerator
    Visibility: public
    Type: instance method
    Input parameters: empty
    Return type: int
    Return the instance variable numerator
  2. Create a getDenominator method with the following signature
    Name: getDenominator
    Visibility: public
    Type: instance method
    Input parameters: empty
    Return type: int
    Return the instance variable denominator

Notice here that we have created accessors to return numerator and denominator. But we have not created any mutators for numerator and denominator. So numerator and denominator of a Fraction object cannot be changed directly.