Presentation is loading. Please wait.

Presentation is loading. Please wait.

Extending classes with inheritance Learning objectives By the end of this lecture you should be able to: explain the term inheritance; design inheritance.

Similar presentations


Presentation on theme: "Extending classes with inheritance Learning objectives By the end of this lecture you should be able to: explain the term inheritance; design inheritance."— 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 method overriding and method overloading; explain the term type cast and 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 Employee Full-time Employee Part-time Employee BankAccount Interest Account

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; PartTimeEmployee is a kind of Employee InterestAccount is a kind of BankAccount Car is a kind of Vehicle Monitor i s not a kind of Computer

4 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 superclasssubclass base classderived class

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)); } RUN Employee Number? Walter Wallcarpeting A103456 310.0 Employee's Name? Hourly Pay? Hours worked this week? A103456 Walter Wallcarpeting 15.50 20

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

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

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 **** **** **** ************ <NEW LINE><NEW LINE> ‘\n’ for (int j = 1; j <= length; j++) { s = s + symbol; } s = s + '\n'; for (int i = 1; i <= height; i++) { } <NEW LINE>

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)

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 Method overriding Customer name : String totalMoneyPaid : double totalGoodsReceived : double Customer(String) getName() : String getTotalMoneyPaid() : double getTotalGoodsReceived() : double calculateBalance() : double recordPayment(double) dispatchGoods(double) : boolean 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 Customer firstCustomer = new Customer("Jones"); GoldCustomer secondCustomer = new GoldCustomer("Cohen", 500); // more code here firstCustomer.dispatchGoods(98.76); secondCustomer.dispatchGoods(32.44); Effect of overriding methods

22 Abstract classes and methods draw() abstract draw() draw() ShapeCircleTriangle abstract Shape

23 Employee number : String name : String Employee(String, String) setName(String) getNumber() : String getName() : String getStatus() : String FullTimeEmployee annualSalary : double FullTimeEmployee(String, String, double) setAnnualSalary(double) getAnnualSalary() : double calculateMonthlyPay () : double getStatus() : String PartTimeEmployee hourlyPay : double 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 Inheritance and Types Employee e ; PartTimeEmployee p ; FullTimeEmployee f ; getStatus() abstract getStatus() getStatus() Employee PartTimeEmployee FullTimeEmployee 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); } } RUN Full-Time Part-Time

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

31 The Object class Employee PartTimeEmployee FullTimeEmployee String BankAccount Object

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

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 myAccount = objectList.getItem(3); System.out.println(myAccount.getBalance()); (BankAccount) objectList.getItem(3);

35 Wrapper classes QHow 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? AUse a wrapper class. Integer hidden int Integer(int) getValue():int Character hidden char Character(char) getValue():char Double hidden double Double(double) getValue():double 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 Third item Second item First item Part-time employee Full-time employee Full-time employee 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(" ull-time or 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(); } RUN Enter the employee number: 1 Enter the employee's name: Jones <F>ull-time or <P>art-time? f Enter the annual salary: 30000 Enter the employee number: 2 Enter the employee's name: Agdeboye <F>ull-time or <P>art-time? f Enter the annual salary: 35000 Enter the employee number: 3 Enter the employee's name: Sharma <F>ull-time or <P>art-time? p Enter the hourly pay: 15

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


Download ppt "Extending classes with inheritance Learning objectives By the end of this lecture you should be able to: explain the term inheritance; design inheritance."

Similar presentations


Ads by Google