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
{
}
{
}
abstract class WithMethods
{
abstract public void f();
}
{
abstract public void 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);
}
}
{
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: