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:

Leave a Reply

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