1 / 43

Extending classes with inheritance

Extending classes with inheritance. Learning objectives. By the end of this lecture you should be able to:. explain the term inheritance ; design inheritance structures using UML notation; implement inheritance relationships in Java;

tamal
Télécharger la présentation

Extending classes with inheritance

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Extending classes with inheritance Learning objectives By the end of this lecture you should be able to: • explain the term inheritance; • design inheritance structures using UML notation; • implement inheritance relationships in Java; • distinguish between methodoverriding and method overloading; • explain the term type castand implement this in Java; • explain the use of the abstract modifier and the final modifier, when applied to both classes and methods; • describe the way in which all Java classes are derived from the Object class.

  2. Software Reuse BankAccount Employee Interest Account Full-time Employee Part-time Employee

  3. Defining inheritance Inheritance is the sharing of attributes and methods among classes; The inheritance relationship is also often referred to as an is-a-kind-of relationship; PartTimeEmployeeis a kind ofEmployee InterestAccountis a kind ofBankAccount Caris a kind ofVehicle Monitor is not a kind of Computer

  4. base class superclass subclass derived class UML notation for inheritance Employee number : String name : String Employee(String, String) setName(String) getNumber() : String getName() : String PartTimeEmployee hourlyPay : double PartTimeEmployee(String, String, double) setHourlyPay(double) getHourlyPay() :double calculateWeeklyPay(int) :double

  5. public class Employee { private String number; private String name; public Employee(String numberIn, String nameIn) { number = numberIn; name = nameIn; } public void setName(String nameIn) { name = nameIn; } public String getNumber() { return number; } public String getName() { return name; } }

  6. public class PartTimeEmployee extends Employee { private double hourlyPay; public PartTimeEmployee(String numberIn, String nameIn, double hourlyPayIn) { super(numberIn, nameIn); hourlyPay = hourlyPayIn; } public double getHourlyPay() { return hourlyPay; } public void setHourlyPay(double hourlyPayIn) { hourlyPay = hourlyPayIn; } public double calculateWeeklyPay(int noOfHoursIn) { return noOfHoursIn * hourlyPay; } }

  7. public class PartTimeEmployeeTester { public static void main(String[] args) { String number, name; double pay; int hours; PartTimeEmployee emp; System.out.print("Employee Number? "); number = EasyScanner.nextString(); System.out.print("Employee's Name? "); name = EasyScanner.nextString(); System.out.print("Hourly Pay? "); pay = EasyScanner.nextDouble(); System.out.print("Hours worked this week? "); hours = EasyScanner.nextInt(); emp = new PartTimeEmployee(number, name, pay); System.out.println(); System.out.println(emp.getName()); System.out.println(emp.getNumber()); System.out.println(emp.calculateWeeklyPay(hours)); } }

  8. public class PartTimeEmployeeTester { public static void main(String[] args) { String number, name; double pay; int hours; PartTimeEmployee emp; System.out.print("Employee Number? "); number = EasyScanner.nextString(); System.out.print("Employee's Name? "); name = EasyScanner.nextString(); System.out.print("Hourly Pay? "); pay = EasyScanner.nextDouble(); System.out.print("Hours worked this week? "); hours = EasyScanner.nextInt(); emp = new PartTimeEmployee(number, name, pay); System.out.println(); System.out.println(emp.getName()); System.out.println(emp.getNumber()); System.out.println(emp.calculateWeeklyPay(hours)); } } Employee Number? A103456 Employee's Name? Walter Wallcarpeting Hourly Pay? 15.50 Hours worked this week? 20 Walter Wallcarpeting A103456 310.0 RUN

  9. Oblong myOblong = new Oblong(6.5, 9.2); 9.2 6.5 Extending the Oblong class ********* ********* ********* ********* ********* *********

  10. Oblong length : double height : double Oblong(double, double) setLength(double) setHeight(double) getLength() : double getHeight() : double calculateArea() : double calculatePerimeter() : double ExtendedOblong symbol : char ExtendedOblong(double, double, char) setSymbol(char) draw() : String

  11. public class ExtendedOblong extends Oblong { private char symbol; public ExtendedOblong (double lengthIn, double heightIn, char symbolIn) { super(lengthIn, heightIn); symbol = symbolIn; } public void setSymbol(char symbolIn) { symbol = symbolIn; } public String draw() { // code to produce String goes here } }

  12. The new-line character **** **** **** ‘\n’ ‘\n’ **** **** **** ‘\n’ <NEW LINE> <NEW LINE> <NEW LINE> for (int j = 1; j <= length; j++) { s = s + symbol; } s = s + '\n'; for (int i = 1; i <= height; i++) { }

  13. public String draw() { String s ; int length, height; length = getLength(); height = getHeight(); for (int i = 1; i <= height; i++) { for (int j = 1; j <= length; j++) { s = s + symbol; } s = s + '\n'; } return s; } } = “ “; = new String(); (int) (int)

  14. ********** ********** ********** ********** ********** ++++++++++ ++++++++++ ++++++++++ ++++++++++ ++++++++++ public class ExtendedOblongTester { public static void main(String[] args) { ExtendedOblong extOblong = new ExtendedOblong(10,5,'*'); System.out.println(extOblong.draw()); extOblong.setSymbol('+'); System.out.println(extOblong.draw()); } } RUN

  15. Customer name : String totalMoneyPaid : double totalGoodsReceived : double Customer(String) getName() : String getTotalMoneyPaid() : double getTotalGoodsReceived() : double calculateBalance() : double recordPayment(double) dispatchGoods(double) : boolean Method overriding GoldCustomer creditLimit : double GoldCustomer(String, double) getCreditLimit() : double setCreditLimit(double) dispatchGoods(double) : boolean

  16. public class Customer { protected String name; protected double totalMoneyPaid; protected double totalGoodsReceived; public Customer(String nameIn) { name = nameIn; totalMoneyPaid = 0; totalGoodsReceived = 0; } // more methods go here }

  17. public String getName() { return name; } public double getTotalMoneyPaid() { return totalMoneyPaid; } public double getTotalGoodsReceived() { return totalGoodsReceived; } public double calculateBalance() { return totalMoneyPaid - totalGoodsReceived; }

  18. public void recordPayment(double paymentIn) { totalMoneyPaid = totalMoneyPaid + paymentIn; } public boolean dispatchGoods(double goodsIn) { if(calculateBalance() >= goodsIn) { totalGoodsReceived = totalGoodsReceived + goodsIn; return true; } else { return false; } }

  19. public class GoldCustomer extends Customer { private double creditLimit; public GoldCustomer(String nameIn, double limitIn) { super(nameIn); creditLimit = limitIn; } public void setCreditLimit(double limitIn) { creditLimit = limitIn; } public double getCreditLimit() { return creditLimit; } // code for dispatchGoods }

  20. public boolean dispatchGoods(double goodsIn) { if((calculateBalance() + creditLimit) >= goodsIn) { totalGoodsReceived = totalGoodsReceived + goodsIn; return true; } else { return false; } }

  21. Effect of overriding methods Customer firstCustomer = new Customer("Jones"); GoldCustomer secondCustomer = new GoldCustomer("Cohen", 500); // more code here firstCustomer.dispatchGoods(98.76); secondCustomer.dispatchGoods(32.44);

  22. Shape Circle Triangle Abstract classes and methods abstract Shape abstract draw() draw() draw()

  23. Employee number : String name : String Employee(String, String) setName(String) getNumber() : String getName() : String getStatus() : String FullTimeEmployee PartTimeEmployee hourlyPay : double annualSalary : double FullTimeEmployee(String, String, double) setAnnualSalary(double) getAnnualSalary() : double calculateMonthlyPay () : double getStatus() : String PartTimeEmployee(String,String, double) setHourlyPay(double) getHourlyPay() : double calculateWeeklyPay(int) : double getStatus() : String An Example

  24. public abstract class Employee { // attributes as before // methods as before abstract public String getStatus(); }

  25. public class PartTimeEmployee extends Employee { // code as before public String getStatus() { return "Part-Time"; } }

  26. public class FullTimeEmployee extends Employee { private double annualSalary; public FullTimeEmployee(String numberIn, String nameIn, double salaryIn) { super(numberIn,nameIn); annualSalary = salaryIn; } // other methods here }

  27. public void setAnnualSalary(double salaryIn) { annualSalary = salaryIn; } public double getAnnualSalary() { return annualSalary; } public double calculateMonthlyPay() { return annualSalary/12; } public String getStatus() { return "Full-Time"; }

  28. abstract getStatus() Employee getStatus() getStatus() PartTimeEmployee FullTimeEmployee Inheritance and Types Employee e ; PartTimeEmployee p ; FullTimeEmployee f ; public class StatusTester { public static void tester(Employee employeeIn) { System.out.println(employeeIn.getStatus()); } }

  29. public class RunStatusTester { public static void main(String[] args) { FullTimeEmployee fte = new FullTimeEmployee("100", "Patel", 30000); PartTimeEmployee pte = new PartTimeEmployee("101", "Jones", 12); StatusTester.tester(fte); StatusTester.tester(pte); } } Full-Time Part-Time RUN

  30. SomeClass someMethod() AnotherClass someMethod() The final modifier final double PI = 3.1417; public final class SomeClass { // code goes here } public final void someMethod() { // code goes here } final SomeClass final someMethod()

  31. Employee PartTimeEmployee FullTimeEmployee The Object class Object BankAccount String

  32. Generic Arrays Bank This array can only hold BankAccount objects private BankAccount[] list; EmployeeList This array can only hold Employee objects private Employee[] list; ObjectList This array can only hold any type of objects private Object[] list;

  33. Generic Methods - add public boolean add( BankAccount itemIn) { if (!isFull()) { list[total] = itemIn; total++; return true; } else { return false; } } Object objectList.add( new BankAccount(“007”, “James Bond”) ) ;

  34. Generic Methods - getItem public BankAccount getItem(int positionIn) { if(positionIn < 1 || positionIn > total) { return null; } else { return list[positionIn - 1]; } } Object (BankAccount) objectList.getItem(3); BankAccount myAccount = objectList.getItem(3); System.out.println(myAccount.getBalance());

  35. Integer hidden int Integer(int) getValue():int Character hidden char Character(char) getValue():char Double hidden double Double(double) getValue():double Wrapper classes Q How could you use an array of Objects to store a simple type such as an int or a char - or to pass such a type to a method that expects an Object? A Use a wrapper class. objectList.add( new Integer( 37)) ;

  36. Autoboxing Object[] anArray = new Object[20]; anArray[0] = new Integer(37); Java 5.0 allows us to make use of a technique known as autoboxing: anArray[0] = 37;

  37. Unboxing Integer intObject = (Integer) anArray[0]; int x = intObject.getValue(); Java 5.0 allows us to make use of a technique known as unboxing: int x = (Integer) anArray[0];

  38. A mixed list Part-time employee Third item Full-time employee Second item Full-time employee First item Employee[] employeeList = new Employee[3];

  39. public class MixedListTester { public static void main(String[] args) { Employee[] employeeList = new Employee[3]; String num, name; double pay; char status; for(int i = 0; i < employeeList.length; i++) { System.out.print("Enter the employee number: "); num = EasyScanner.nextString(); System.out.print("Enter the employee's name: "); name = EasyScanner.nextString(); System.out.print("<F>ull-time or <P>art-time? "); status = EasyScanner.nextChar(); // more code here }

  40. if(status == 'f' || status == 'F') { System.out.print("Enter the annual salary: "); } else { System.out.print("Enter the hourly pay: "); } pay = EasyScanner.nextDouble(); if(status == 'f' || status == 'F') { employeeList[i] = new FullTimeEmployee(num, name, pay); } else { employeeList[i] = new PartTimeEmployee(num, name, pay); } System.out.println(); } // end of loop

  41. for(Employee item : employeeList) { System.out.println("Employee number: " + item.getNumber()); System.out.println("Employee name: " + item.getName()); System.out.println("Status: " + item.getStatus()); System.out.println(); }

  42. public class MixedListTester { public static void main(String[] args) { Employee[] employeeList = new Employee[3]; // declare local variables to hold values entered by user String num, name; double pay; char status; for(int i = 0; i < employeeList.length; i++) { System.out.print("Enter the employee number: "); num = EasyScanner.nextString(); System.out.print("Enter the employee's name: "); name = EasyScanner.nextString(); System.out.print("<F>ull-time or <P>art-time? "); status = EasyScanner.nextChar(); if(status == 'f' || status == 'F') { System.out.print("Enter the annual salary: "); } else { System.out.print("Enter the hourly pay: "); } pay = EasyScanner.nextDouble(); if(status == 'f' || status == 'F') { employeeList[i] = new FullTimeEmployee(num, name, pay); } else { employeeList[i] = new PartTimeEmployee(num, name, pay); } System.out.println(); } for(Employee item : employeeList) { System.out.println("Employee number: " + item.getNumber()); System.out.println("Employee name: " + item.getName()); System.out.println("Status: " + item.getStatus()); System.out.println(); } } } Enter the employee number: 1 Enter the employee's name: Jones f <F>ull-time or <P>art-time? Enter the annual salary: 30000 Enter the employee number: 2 Enter the employee's name: Agdeboye f <F>ull-time or <P>art-time? Enter the annual salary: 35000 Enter the employee number: 3 Enter the employee's name: Sharma p <F>ull-time or <P>art-time? Enter the hourly pay: 15 RUN

  43. Employee number: 1 Employee name: Jones Status: Full-Time Employee number: 2 Employee name: Agdeboye Status: Full-Time Employee number: 3 Employee name: Sharma Status: Part-Time RUN

More Related