CH7 – Encapsulation and Generalization

  1. Create a new class namedĀ EncapGen and add the following code to main so the class appears as follows.
public class EncapGen {
  public static void main(String[] args){
    int i = 1;
    while (i <= 6){
      System.out.printf("%4d",2*i);
      i=i+1;
    }
    System.out.println();
  }
}
  1. Compile and run the program.
$ javac EncapGen.java
$ java EncapGen
   2   4   6   8  10  12
  1. Add a new method called printRow and move the code from main to printRow.
public class EncapGen {
  public static void main(String[] args){
    printRow();
  }
  public static void printRow(){
    int i = 1;
    while (i <= 6){
      System.out.printf("%4d",2*i);
      i=i+1;
    }
    System.out.println();
  }
}
  1. Compile and run the program and the results are the same.
  2. Modify printRow so that it takes an integer as a parameter.
  3. Change the numeral two in the printf statement to the variable name passed to printRow as a parameter.
  4. Change the call to printRow in main to pass the numeral 2 as the argument. The class should now appear as follows.
public class EncapGen {
  public static void main(String[] args){
    printRow(2);
  }
  public static void printRow(int n){
    int i = 1;
    while (i <= 6){
      System.out.printf("%4d",n*i);
      i=i+1;
    }
    System.out.println();
  }
}
  1. Compile and run the program and the results are the same.
$ javac EncapGen.java
$ java EncapGen
   2   4   6   8  10  12