Object Oriented Concepts Practice Problems


  1. Rational numbers contain an integer numerator and denominator. Write the code to implement a class named Rational which stores two private ints (numer and denom) with the following methods:
      public Rational(int,int);  //constructor that sets the numer and denom
      public Rational(Rational); //copy constructor for a Rational object
    
      public void setNumer(int); //sets the numerator to the paramter value
      public int getNumer();     //returns the stored numerator
      public void setDenom(int); //sets the denominator to the paramter value
      public int getDenom();     //returns the stored denominator
    
      //return a new Rational object that contains the reciprocal of the object that invokes the method.
      public Rational reciprocal();
    
      //returns a new Rational object that contains the product of the two paramteres.
      public static Rational multiply(Rational a, Rational b);  

  2. Implement a class named Cat such that objects of that type will contain a name and a number of lives and the class will keep track of how many Cat objects were ever created. The class will also have the following methods:
      //returns the number of lives the object that invoked the method has left
      public int getLives();    
    
      //decreases the number of lives of the object that invoked the method
      //  and returns true if it has any left but returns false if it is out
      //  of lives according to the int it holds
      public boolean useLife();
    
      //returns the number of Cat objects ever created
      public static int getCatsEver();
    
      //returns a String of the form
      //   Cat cat_name has # lives left.
      //or
      //   Cat cat_name has passed away.
      //depending on whether or not the number of lives has gone negative
      public String toString();