Exercise 12      Name                                    Points __/30

Document last modified: 

  1. (1) What is the output of the program at right? 12 2
     
  2. (1) What is the value of field S for the object referenced by a12 at the end of program execution? 2

public class Twelve {

   public static void main(String args[]) {
        A a12 = new A(12);

        a12.print(2);
        a12.print(2);
   }
}

class A {
   private int S;

   public A (int S) { this.S = S; }

   public void print (int S) {
      System.out.println( this.S );
      this.S = S;
   }
}

 

  1. (2) What is the output of the program at right?
    red
    white
    15.0
    15.0
     

(8) Diagram, in a manner similar to that above, the objects referenced by a12 and b12; show classes A and B.

  1. (18) Indicate which are syntactically INVALID in the method main. For those that are syntactically VALID, indicate which cause a runtime error.

          Syntax  Runtime

    1. ____    ____   a12.getS();
    2. ____    ____   b12.getS();
    3. _IV_    ____   a12.getD();
    4. _IV_    ____   b12 = a12;
    5. ____    ____   a12 = (A)b12;
    6. ____    RTE    b12 = (B)a12;
    7. ____    ____   a12 = b12;
    8. ____    RTE    ((B)a12).getD();
    9. _IV_    ____   ((A)b12).getD();
public class Twelve {
   public static void main(String args[]) {

      A a12 = new A("red");
      a12.print();

      B b12 = new B(15.0, "white");
      b12.print();

      System.out.println( b12.getD() );
   }
}

class A {
   private String S;

   public A (String S) { this.S = S; }

   public void print () {
      System.out.println( this.S );
   }
 
   public String getS () { return this.S; }

}

class B extends A {
   private double D;

   public B (double D, String S) {
      super(S);
      this.D = D;
   }

   public void print () {
      super.print( );
      System.out.println( this.D );
   }

   public double getD () { return this.D; }
}