Inheritance Review

Consider the Face, HappyFace and Bunny classes for these questions. Suppose there is also a class called HairyHappyFace that has the following extra field:

int hairLength;

and the following methods:

public void cutHair(int amountToCut) - subtracts amountToCut from hairLength (if you end up with a negative value then set hairLength to zero)
public void wink (int howMany) - if hairLength is greater than 10 then wink won't do anything since the eye will be covered by the hair, otherwise do the same as the inherited version.

  1. State which of the following are invalid and state why.

    1. Face f = new Bunny(this);
      HappyFace hf = (HappyFace)f;
      hf.wink(10);
    2. Face f = new HappyFace(this);
      f.wink(10);
    3. HairyHappyFace hhf = new HairyHappyFace(this);
      hhf.cutHair(5);
      hhf.wink(10);
      hhf.setEyeColor(Color.green);
    4. Bunny b = new Face(this);
      b.hop(5, 10);
    5. Bunny b;
      b.hop(5, 10);
      b.setSurprise(true);
      b.setEarColor(Color.yellow);
    6. Face f = new HairyHappyFace(this);
      f.setVisible(true);
      f.move(100, 100);
  2. In the last part of the previous question, which version of move would be called?
  3. Write the code for the HairyHappyFace class (but don't bother with the draw and erase methods).
  4. Consider the following classes:

    public class Parent
    {
       int x;
       
       public Parent(int val)
       {
          x = val;
       }
       
       public void someMethod()
       {
          System.out.println("This is from class parent");
       }
       
       public void someMethod(int y)
       {
          x = y;
       }
       
       public String toString()
       {
          System.out.println(super.toString());
          return "x = " + x;
       }
       
    } 
    public class Child extends Parent
    {
       
       public Child(int y)
       {
          super(y);
       }
          
       public void someMethod()
       {
          System.out.println("In the class Child");
       }
       
       public void newMethod()
       {
          System.out.println("This is not in parent");
       }
       
       public static void main(String[] args)
       {
          Parent p = new Parent(5); // Stored in location 25e8c942 
          p.someMethod();
          Child c = new Child(10); // Stored in location 15ef19ab 
          c.someMethod();
    
          p = new Child(20); // Stored in location 15db9742 
          p.someMethod();
          //p.newMethod();
          c = (Child)p;
          c.newMethod();
          System.out.println(c);
       }
    } 

    1. What would happen if the commented out statement was included in the class Child?
    2. What would the output be from the Child application?
    3. What is an example of an overloaded method above?
    4. What is an example of an overridden method above?