I seem to not understand two OOP concepts very well. Could you explain what abstraction and polymorphism are, preferably with real examples and
These two are among the most important characteristics of Object Oriented paradigm.
Object orientation models the software as real world objects. However it would be too hard ( and useless ) to model ALL the properties a Customer may have, or all the properties an Employee have.
By listing only the interesting attributes of an object OO may use effectively that object for an specific domain. That's abstraction.
For instance an Employee in a HR system may have very different attributes than a Online BookStore. We abstract the details to make is useful.
Objects may behave differently depending on the "type" while keeping the same interface.
What does this means?
For instance an online store system may have two sub-classes of Employee
A) Internal employees.
B) Contractors
And a method to calculate the discount for internal purchases
The discount of an internal employee is calculated as: 10% + 2% for each worked year in the company + 2% for each.. mmhh child
The discount of a contractor is 10%
The following code to calculate the amount to pay:
public Amount getAmountToPay( Product product, Employee internalCustomer ) {
Amount amount = product.getPrice();
amount.applyDiscount( internalCustomer.getDiscount() );
return amount;
}
Would produce different results for the two different kinds of Employee 's
class Employee {
public int getDiscount();
}
class InternalEmployee extends Employee {
public int getDiscount() {
return 10 + 2 * getWorkedYears() + 2 * getNumberOfChilds();
}
}
class Contractor extends Employee {
public int getDiscount() {
return 10;
}
}
This is the polymorphism in action. Instead of having something like
Amount amount = product.getPrice();
if( employee.isContractor() ) {
amount.applyDiscount( 10 );
} else if( employee.isSomthingElse() ) {
amount.applyDiscount( 10 * 2 * getYrs() + 2 * getChilds() );
} else if ( employee.contidions, condigions, conditions ) {
amount.applyDiscount( getSomeStrageRuleHere() );
}
We let the runtime to choose which one to calculate. Is like the program behaves differently depending on the type:
Amount amount = product.getPrice();
amount.applyDiscount( internalCustomer.getDiscount() );
return amount;
By the way, in this example the "Amount" is an abstraction of a real life concept, that could also be represented as a double or an Integer, but maybe we have interestion methods inside that would be better if set in its own class.
I hope this helps.