430 likes | 669 Views
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;
E N D
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.
Software Reuse BankAccount Employee Interest Account Full-time Employee Part-time Employee
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
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
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; } }
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; } }
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)); } }
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
Oblong myOblong = new Oblong(6.5, 9.2); 9.2 6.5 Extending the Oblong class ********* ********* ********* ********* ********* *********
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
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 } }
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++) { }
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)
********** ********** ********** ********** ********** ++++++++++ ++++++++++ ++++++++++ ++++++++++ ++++++++++ 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
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
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 }
public String getName() { return name; } public double getTotalMoneyPaid() { return totalMoneyPaid; } public double getTotalGoodsReceived() { return totalGoodsReceived; } public double calculateBalance() { return totalMoneyPaid - totalGoodsReceived; }
public void recordPayment(double paymentIn) { totalMoneyPaid = totalMoneyPaid + paymentIn; } public boolean dispatchGoods(double goodsIn) { if(calculateBalance() >= goodsIn) { totalGoodsReceived = totalGoodsReceived + goodsIn; return true; } else { return false; } }
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 }
public boolean dispatchGoods(double goodsIn) { if((calculateBalance() + creditLimit) >= goodsIn) { totalGoodsReceived = totalGoodsReceived + goodsIn; return true; } else { return false; } }
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);
Shape Circle Triangle Abstract classes and methods abstract Shape abstract draw() draw() draw()
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
public abstract class Employee { // attributes as before // methods as before abstract public String getStatus(); }
public class PartTimeEmployee extends Employee { // code as before public String getStatus() { return "Part-Time"; } }
public class FullTimeEmployee extends Employee { private double annualSalary; public FullTimeEmployee(String numberIn, String nameIn, double salaryIn) { super(numberIn,nameIn); annualSalary = salaryIn; } // other methods here }
public void setAnnualSalary(double salaryIn) { annualSalary = salaryIn; } public double getAnnualSalary() { return annualSalary; } public double calculateMonthlyPay() { return annualSalary/12; } public String getStatus() { return "Full-Time"; }
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()); } }
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
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()
Employee PartTimeEmployee FullTimeEmployee The Object class Object BankAccount String
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;
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”) ) ;
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());
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)) ;
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;
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];
A mixed list Part-time employee Third item Full-time employee Second item Full-time employee First item Employee[] employeeList = new Employee[3];
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 }
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
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(); }
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
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