Question: What is the output of this code? Why? class GrandParent { } class Parent extends GrandParent{ } class Child extends Parent { } class Foo

  1. What is the output of this code? Why?

     class GrandParent { } class Parent extends GrandParent{ } class Child extends Parent { } class Foo { public void bar(GrandParent p) { System.out.println("called with type GrandParent"); } public void bar(Parent p) { System.out.println("called with type Parent"); } } public class Test { public static void main(String[] args) { new Foo().bar(new Child()); } } 
  2. In this exercise we will try to see how static and final methods work with inheritance. (A final method is one that cannot be overridden in a subclass.) Consider the two classes defined below, Parent and Child:

     public class Parent { /* public static final void printClassName() { System.out.println("I am in class Parent, static invocation."); } */ public final void printName() { System.out.println("I am in class Parent, dynamic invocation."); } } public class Child extends Parent { /* public static void printClassName() { System.out.println("I am in class Child, static invocation."); } */ public void printName() { System.out.println("I am in class Child, dynamic invocation."); } } 
    1. Compile both the classes. What do you see?
    2. Now comment out the printName() method in the Child class and uncomment the printClassName() method in both classes. Compile both classes. What do you see? Is it different from part (A)? Why?
    3. Uncomment the Child.printName() method and remove the final modifier from Parent.printName() and Parent.printClassName(). Recompile both classes.
    4. Compile and run the following class:
       class App { public static void main(String[] args) { Parent p = new Child(); p.printName(); // WHAT IS PRINTED? p.printClassName(); // WHAT IS PRINTED? } } 
      Explain the difference in which methods are invoked in these two method calls.
  3. Here's a Widget class:
     public class Widget { float mass; private static float MAX_MASS = 20; public static final float G = 9.81f; public Widget(float mass) { if (mass > MAX_MASS) { throw new IllegalArgumentException(); } this.mass = mass; } public static float getMaxMass() { return MAX_MASS; } public float getWeight() { return mass*G; } } 
    Now suppose there is a certain set of widgets that are "heavy", so their maximum mass is 40 instead of the usual 20. Write a class called HeavyWidget, as a subclass of Widget. Do you encounter any implementation issues when you do this? Can you get around these issues? If so, show how. If not, explain why.

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!