Thinking in Java Fourth Edition Bruce Eckel Chapter 8 Exercise 4

Exercise 4: Create an abstract class with no methods. Derive a class and add a method. Create a static method that takes a reference to the base class, downcasts it to the derived class, and calls the method. In main( ), demonstrate that it works. Now put the abstract declaration for the method in the base class, thus eliminating the need for the downcast.

Solution:

abstract class NoMethods
{
}
class Extended1 extends NoMethods
{
    public void f()
    {
        System.out.println("Extended1.f");
    }
}
abstract class WithMethods
{
    abstract public void f();
}
class Extended2 extends WithMethods
{
    public void f()
    {
        System.out.println("Extended2.f");
    }
}
public class E04
{
    public static void test1(NoMethods nm)
    {
        // Must downcast to access f():
        ((Extended1)nm).f();
    }
    public static void test2(WithMethods wm)
    {
        // No downcast necessary:
        wm.f();
    }
    public static void main(String args[])
    {
        NoMethods nm = new Extended1();
        test1(nm);
        WithMethods wm = new Extended2();
        test2(wm);
    }
}

Output:

Leave a Reply

Your email address will not be published. Required fields are marked *