Objects and Classes

Exercises


  1. Create a class ConstructorTest with a constructor that takes no arguments and prints a message like "Object constructed". Create an object of this class.
  2. Overload the constructor in the class ConstructorTest with a new constructor which takes a String argument and prints it along with the message from Exercise 1.
  3. Create a two dimensional array myValues of int values and a two dimensional array myObjects of Objects of class Integer. Both arrays should be of the following dimensions: The outer array has three fields. The first inner array has two fields, the second inner array has four fields, and the third inner array has two fields.Compare the creation of te two arrays. Print out the array content of one of the arrays that reflects the array structure.
  4. Create a class Counter with an adequate data member. Write four methods, one to get the value of the counter (getValue), one to increment the counter (increment), one to decrement the counter (decrement), and one to reset the counter to zero (reset). 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 getValue-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.) Alternatively you may also use a "greatest common divisor" Algorithm for this purpose.

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


Software Systems Institute

Home of the Java Course Claudia Niederée, nov 1999