Inheritance and Design CSIS 3701: Advanced Object Oriented Programming.
-
Upload
tracy-morgan -
Category
Documents
-
view
220 -
download
0
Transcript of Inheritance and Design CSIS 3701: Advanced Object Oriented Programming.
Inheritance and Design
CSIS 3701: Advanced Object Oriented Programming
Key Questions
Given list of required classes:
• What classes should extend others?• Are additional classes needed?• What methods can be inherited/overridden?• Do methods need to be designed for
polymorphism?
“Employees” Example
• Goal: “Payroll” system prints weekly paychecks– Paycheck of form “Pay for name: $amount”– Also tracks total pay for all employees– Should store information in single data structure
• Problem: Many types of workers paid in different ways
“Employees” Example
Employee types:
• Salaried: Yearly salary / 52
• Manager: Like salaried, with additional weekly bonus
• Intern: Paid hourly rate for hours worked (may be different every week). Cannot work over 40 hours.
• Consultant: Paid hourly rate for hours worked (may be different every week), with additional travel allowance
Polymorphism and Class Design
• Is polymorphism necessary?– All objects in single container or manipulated by single
method (add method in JPanel)
• What methods must be polymorphic?– Will be iterated for all objects in container, etc.
– Must be defined in superclass
• Example:
– All employees stored in single array (polymorphism needed)
– Will call getPay() and getCheck() for each
Hierarchy Design
• Inheritance hierarchy often “tree” structure– Required classes often “leafs”– Overall superclass at “root”– Abilities inherited along “branches”
Consultant
InternSalaried
Manager
?????
Superclass Identification
• What abilities/information are common to all required classes?– Defines overall superclass at root of hierarchy
• Example: All employees have– A name– Ability to compute weekly pay– Ability to print name/pay on paycheck
Superclass Identification
• Employee superclass:
ConsultantIntern
SalariedManager
Employee
String name;double getPay();String getCheck();
Abstract Classes
• Problem: Users should not be able to create instances of Employee – Only exists to define common features of actual
required classes– Will not actually have all required abilities for use
Employee e = new Employee();
double p = e.getPay();
This is not defined for generic “employee”
Abstract Classes
• Can define class as abstract– Cannot be instantiated– Very common in Java
Example: abstract JComponent class• Superclass of all visual swing components• Defines common properties of x, y, width, height
public abstract class Employee {
private String name;
public Employee(String n) name = n;
…
}
Abstract Methods
• Often need to “declare” a method in superclass without actually defining it
• Example: getPay() method in Employee class– No way to provide actual definition at this level– Necessary if polymorphism required
Employee e = new Salaried(“Fred”, 26000);
pay = e.getPay();
Will not work unless getPay() in Employee class
Abstract Methods
• Can declare method abstract in superclass– Must be overridden in subclasses– Often used to enable polymorphism– Form like C++ “prototypes”
public abstract returntype methodname(params);
Final “Employee” Superclass
public abstract class Employee {
private String name;
public Employee(String n){name = n;}
public abstract double getPay();
public String getCheck() {
return "Pay for "+name+": \t$"+ getPay();
}
}• Can still define getCheck even if calls abstract method
– Will only be invoked on subclass objects– Those will use their overridden version of getPay()
Hierarchical Decomposition
• What do some classes have in common?
– Salaried and Manager have salary– Intern and Consultant have hours worked, rate of pay, and
method to set hours
• What must those classes do differently?
– Manager also has bonus– Consultant also has travel allowance – Intern must validate that hours ≤ 40
Must look at data and methods
Hierarchical Decomposition
• Are the abilities of one class a subset of another?– One class has all the same abilities as another, and
some additional abilities
• If so, make C2 subclass of C1
data methoddata methoddata method
…
additional data method data method
…
C1 C2
Supervisor/Manager Example
• Salaried: – Stores name (inherited from Employee), salary– Computes pay as salary/52
• Manager: – Stores name , salary, and bonus– Computes pay as salary/52 + bonus
• Manager should be subclass of Salaried
Hierarchical Decomposition
• Do abilities of different classes intersect– Classes have shared abilities, but neither subset of other
• If so, create abstract class with shared abilites– Both classes now extend it
data method shared datadata method shared method
data method data method
C1 C2
New abstract C3
Hierarchical Decomposition
• Commonly done in Java• Example: JTextComponent class
JComponentint x, y, width, height
Common to all visual components
JTextComponentString textString getText()void setText(String)
Common to visual components that accept text
JTextField JTextArea
Consultant / Intern Example
• Consultant: – Stores name, hours, rate, travel
– Computes pay as hours * rate + travel
– Has method to set hours
• Intern: – Stores name, hours, rate
– Computes pay as hours * rate
– Has method to set hours which must validate ≤ 40
• Create Hourly class with shared abilities
Consultant / Intern Example
Hourlyint hours, double rate set by constructorgetPay(): hours * ratesetHours(h): hours = h
Consultantdouble travelgetPay(): superclass version + travel
InternsetHours(h): check h <= 40 before calling superclass version
Final Hierarchy Design
Employee(abstract)
Salaried
Manager
Hourly(abstract)
Intern Consultant
Method Design
• Design methodologies:
– Subclass methods should only directly manipulate subclass variables
– Subclass methods should (if possible) call superclass version to manipulate inherited superclass variables
Supervisor/Manager Example
Salarieddouble salarygetPay(): salary/52
Managerdouble bonusgetPay(): salary/52 + bonus
superclass version of getPay
Salaried Class
public class Salaried extends Employee {
private double salary; // Yearly salary
public Salaried(String n, double s) {
super(n);
salary = s;
}
public double getPay() {
return salary/52;
}
}
Manager Class
public class Manager extends Salaried {
private double bonus;
public Manager(String n, double s, double b) {
super(n, s);
bonus = b;
}
public double getPay() {
return super.getPay() + bonus;
}
}
Hourly Classpublic abstract class Hourly extends Employee {
private double rate; // Hourly pay rate
private int hours; // hours worked this week
public Hourly(String n, double r) {
super(n);
rate = r;
hours = 0;
}
public void setHours(int h) {
hours = h;
}
public double getPay() {
return hours * rate;
}
}
Consultant Class
public class Consultant extends Hourly {
private double travel; // Travel allowance
public Consultant(String n, double r, double t) {
super(n, r);
travel = t;
}
public double getPay() {
return super.getPay() + travel;
}
}
Intern Class
public class Intern extends Hourly {
public Intern(String n, double r) {
super(n, r);
}
public void setHours(int h) {
if (h > 40) {
h = 40;
}
super.setHours(h);
}
}
Encapsulation
• Access to superclass variables may not be possible with public methods
• superclass should provide protected methods to allow access to superclass variables
• Example:– Intern class must print message with employee
name if error– Employee must provide protected method to allow
access to name
Encapsulation
public abstract class Employee {
private String name;
…
protected String getName() {return name;}
public class Intern extends Hourly {
…
public void setHours(int h) {
if (h > 40) {
System.out.println(getName()+ ” can only work 40 hours”);
}
else super.setHours(h);
}
Polymorphism
• Create objects in different classes
public static void main(String[] args) {Salaried wally = new Salaried("Wally", 52000);
Salaried alice = new Salaried("Alice", 78000);
Manager phb = new Manager("Pointy Haired Boss", 104000, 200);
Intern asok = new Intern("Asok", 20);
asok.setHours(50);
Consultant dogbert = new Consultant("Dogbert", 100, 500);
dogbert.setHours(42);
Polymorphism
• Store in single data structure
Employee[] workers = new Employee[5];
workers[0] = phb;
workers[1] = alice;
workers[2] = wally;
workers[3] = asok;
workers[4] = dogbert;
Polymorphism
• Manipulate as though instances of superclass
double total = 0;
for (int i = 0; i < 5; i++) {
System.out.println(workers[i].getCheck());
total += workers[i].getPay();
}
System.out.println("Total pay: \t$" + total);