800 likes | 996 Views
Chapter 6. Reusing Classes. Example: public class Car { Engine engine = new Engine(); Wheel[] wheel = new Wheel[4]; Door left = new Door(); Door right = new Door(); … }. “has a” relationship. Types of Attributes. * 参见程序运行. * 参见程序运行. Reference:. Please:.
E N D
Chapter 6 Reusing Classes
Example: • public class Car { • Engine engine = new Engine(); • Wheel[] wheel = new Wheel[4]; • Door left = new Door(); • Door right = new Door(); • … • } “has a” relationship
Please: Person、 Employee、Customer、Manager、 CSR 的继承树 “is a” relationship
Composition- ”has a” Composition & Inheritance Inheritance -”is a”
class OrderTaker{ private String name; private int basePay; private int ordersTaken; public void setName(String newValue){ name = newValue; } public void setBasePay(int newValue) { basePay = newValue; } public void incrementOrdersTaken() { ordersTaken++; } public String getName() { return name; } public int getBasePay(){ return basePay; } public int getOrdersTaken(){ return ordersTaken; } public double calculatePay() { //Generic order takers get a weekly portion of their salary return getBasePay() / 52; } }
class CSR extends OrderTaker { public double calculatePay(){ //CSRs get their weekly pay plus 10 cents per order they take return getBasePay() / 52 + getOrdersTaken() * .1; } } class OEC extends OrderTaker { public double calculatePay(){ //OECs get their weekly pay plus 1 cent per order they take return getBasePay() / 52 + getOrdersTaken() * .01; } }
class Telemarketer extends OrderTaker{ private int peopleHarassed; public void incrementPeopleHarassed(){ peopleHarassed++; } public int getpeopleHarassed() { return peopleHarassed; } public double calculatePay(){ /*Telemarketers get 10 cents for every order they take and 1cent per person they harass (call)*/ return getBasePay() / 52 + peopleHarassed * .01 + getOrdersTaken() * .1; } }
public class TestPolymorphism{ //class Clerks public static void main(String args[]) { OrderTaker first, second, third; first = new OEC(); second = new CSR(); third = new Telemarketer(); first.setBasePay(52000); second.setBasePay(52000); third.setBasePay(52000); first.incrementOrdersTaken(); first.incrementOrdersTaken(); second.incrementOrdersTaken(); third.incrementOrdersTaken(); ((Telemarketer) third).incrementPeopleHarassed(); System.out.println("First made " + first.calculatePay()); System.out.println("Second made " + second.calculatePay()); System.out.println("Third made " + third.calculatePay()); } }