The Art of Object Oriented Programming

  1. The key to good object oriented programming is to define objects to fulfill a well-defined purpose/need... and only define a class when you have a well-defined purpose/need.

  2. A welcome side effect is that:

    If a class has a well-defined purpose/need, it can be re-used in other programs.

  3. Example problem:

    Write a program that reads in integers between 1 and K and prints number of times that each number appeared in the input. The sequence is terminated by 0.

    Example: if the numbers entered are 1, 2, 3, 1, 1, 1, 2, 2, 1, 0 then the program prints:

         1: 5 times
         2: 3 times
         3: 1 times
    

  4. The convential solution:

    // ***************************************** // Input the numbers... // ***************************************** System.out.print("Enter next number (0 to end): "); nextNumber = console.readInt(); while ( nextNumber != 0 ) { // ***************************************** // Tally // ***************************************** if ( nextNumber >= 1 && nextNumber <= K ) Count[nextNumber] = Count[nextNumber] + 1; // ***************************************** // Ask for next number // ***************************************** System.out.print("Enter next number (0 to end): "); nextNumber = console.readInt(); } // ***************************************** // End of input, print tally statistics.. // ***************************************** System.out.println("The tally is as follows:"); i = 1; while ( i <= K ) { System.out.println(i + ": " + Count[i] + " times"); i = i + 1; }

    The demo program is available here: click here