This example demonstrates the power of object-oriented programming.
Because ab is an instance of B, any method call on ab will use the functions defined in B, even if these functions are called indirectly via a function defined in a superclass.
The example is so abstract that the virtue of this may not be clear. Let me make a slightly more realistic example:
class Employee
{
... bunch of stuff ...
void calcPay()
{
pay=hoursWorked*hourlyRate;
}
void produceCheck))
{
calcPay();
calcTaxes();
calcBenefitDeductions();
printCheck();
}
}
class Salesman extends Employee
{
void calcPay()
{
pay=sales*commissionRate;
}
}
... somewhere else ...
for (Employee employee1 : employeeList)
{
employee1.produceCheck();
}
I'm leaving out all sorts of detail to make the point: This code won't compile.
But here's the point: Salesman have a different method of calculating their pay then other employees: They're paid on commission instead of hourly. (In real life, we'd presumably also have salaried employees, but as I say, I'm simplifying.) The function to calculate pay of either type of employee is called from within a bigger function that also does other things. The beauty of object-oriented programming is that we can call the outside function and not care whether the object we are calling it against is a regular Employee or a Salesman. Each object knows what it is and calls the right function. In the last few lines of the example, we have some structure that includes both regular Employees and Salesmen, and we can loop through and process them all without having to check their type. Without OOP, we'd have to constantly write code like: "if (type == SALESMAN) ... else if (type == HOURLY) ..."