C311 Spring 1998, Assignment 10: Inheritance in Java

Due Tuesday, April 16, 11:59pm


  1. Consider the following set of Java class definitions:
          class A {
            int m1() {
              return 1; 
            }
            int m2() {
              return this.m1(); 
            }
          }
    
          class B extends A {
            int m1() {
              return 2; 
            }
          }
    
          class C extends B {
            int m3() {
              return this.m2(); 
            }
            int m4() {
              return super.m1();
            }
          }
    
          class D extends C {
            int m1() {
              return 3; 
            }
          }
    
    Using only your brain, your classmates, your lecture notes, and the textbook (i.e., without using a Java compiler), write down the result that is returned by each of the following expressions. (Note that some of the expressions would not even compile because they are ill-typed. Write "ill-typed" for these cases.)

    1. (new A()).m1()
    2. (new A()).m2()
    3. (new A()).m3()
    4. (new A()).m4()
    5. (new B()).m1()
    6. (new B()).m2()
    7. (new B()).m3()
    8. (new B()).m4()
    9. (new C()).m1()
    10. (new C()).m2()
    11. (new C()).m3()
    12. (new C()).m4()
    13. (new D()).m1()
    14. (new D()).m2()
    15. (new D()).m3()
    16. (new D()).m4()


  2. Still using only brain, notes, and friends, decide which of the following Java program fragments would be rejected by the typechecker if we compiled them in the presence of the above class definitions (write rejected or accepted). Also, which of them would fail with runtime exceptions if we executed them without typechecking (write fail or ok)? For each fragment that is rejected or that fails, write a short explanation of why.

    For example, the fragment

        (true ? new C() : new A()).m3()
    
    will be rejected by the compiler but would not fail if we ran it. A correct answer would be "rejected / ok".

    1.    int i = (new A()).m1() + 5;
      
    2.    A a = new A();
         int i = a.m3();
      
    3.    C c = new C();
         int i = ((A)c).m1();
      
    4.    B b = new C();
         int i = b.m3();
      
    5.    B b = (A)(new C());
      
    6.    B b = (C)(new A());
      
    7.    class M {
           Integer p() {
             return (new C()).m4();
           }
         }
      
    8.    C[] ca = new C[3];
         B[] ba = ca;
         ba[0] = new B();
         A[] aa = ba;
         int i = (aa[0]).m1();
      
    9.    C[] ca = (C[])(new A[3]);
         ca[0] = (C)(new A());
      


Submission

Submit an ascii email message with the usual subject line, in this format:

    QUESTION 1:

    1.  answer
    2.  answer
    ...

    QUESTION 2:

    1.  answer / answer
        explanation
    2.  answer / answer
        explanation
    ...
Sorry, no automatic grading.