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:

Thinking in Java Fourth Edition Bruce Eckel Chapter 8 Exercise 3

Exercise 3: Create a base class with an abstract print( ) method that is overridden in a derived class. The overridden version of the method prints the value of an int variable defined in the derived class. At the point of definition of this variable, give it a nonzero value. In the base-class constructor, call this method. In main( ), create an object of the derived type, and then call its print( ) method. Explain the results.

Solution:

abstract class BaseWithPrint
{
public BaseWithPrint()
{
print();
}
public abstract void print();
}
class DerivedWithPrint extends BaseWithPrint
{
int i = 47;
public void print()
{
System.out.println("i = " + i);
}
}
public class E03
{
public static void main(String args[])
{
DerivedWithPrint dp = new DerivedWithPrint();
dp.print();
}
}

Ouput: