Objects and Classes

Exercises


  1. Create a class with a default constructor (no arguments) that prints a message. Create an object of this class.
  2. Add an overloaded constructor to the class in 1 which takes a String argument and prints it along with your message.
  3. Make a two dimensional array of objects of the class you created in 2.
  4. Create a class Counter with an adequate data member. Write four methods, one to get the value of the counter, one to increment the counter, one to decrement the counter, and one to reset the counter to zero. Make sure that the value of the counter never gets less than zero.
  5. Create an object of your class Counter and assign it to two different variables. Change the state of the object, calling your method on one variable. See what happens if you call the get-value-method on the other variable.
  6. * Define a class Fraction that represents mathematical fractions like 1/4 or 3/2. Provide data members for the numerator and the denominator. Make sure they are only accessible via methods and that the denominator is not zero. Define a constructor that takes two values of type int and creates a fraction and a method for each of the following purposes
  7. * Test your class Fraction. Insert a method printFraction for this purpose.
  8. * Canceling down fractions, the fraction 4/8 is equal to 1/2. Work over your class Fraction again taking this fact into account. Change at least the implementation of equals. Use the class Sieve for canceling down the fractions. (Hint: Search for prime numbers that are divisors of the denominator as well as of the numerator and divide both parts by this primes.)

The exercises marked with a star (*) are intended as additional opportunities to train your Java knowledge.


Software Systems Institute

Home of the Java Course Ulrike Steffens, nov 1998