Download presentation
Presentation is loading. Please wait.
Published byIsabella Powell Modified over 9 years ago
1
SD1042 Introduction to Software Development
2
Extending classes with inheritance Robot DancingRobot Sharing attributes and methods
3
Extending classes with inheritance Learning objectives 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 when applied to both classes and methods; describe the way in which all Java classes are derived from the Object class.
4
Software Reuse
5
BankAccount InterestAccount InterestAccount is a kind of BankAccount
6
Employee FullTimeEmployee PartTimeEmployee FullTimeEmployee is a kind of Employee PartTimeEmployee is a kind of Employee
7
Representing inheritance in UML diagrams..
8
Employee number : String name : String Employee(String, String) setName(String) getNumber() : String getName() : String PartTimeEmployee number : String name : String hourlyPay : double PartTimeEmployee(String, String, double) setName(String) getNumber() : String getName() : String setHourlyPay(double) getHourlyPay() :double calculateWeeklyPay(int) :double
9
Employee number : String name : String Employee(String, String) setName(String) getNumber() : String getName() : String PartTimeEmployee number : String name : String hourlyPay : double PartTimeEmployee(String, String, double) setName(String) getNumber() : String getName() : String setHourlyPay(double) getHourlyPay() :double calculateWeeklyPay(int) :double
10
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
11
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 UML notation for inheritance
12
Code for the Employee class.. Employee number : String name : String Employee(String, String) setName(String) getNumber() : String getName() : String
13
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; } }
14
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; }
15
Code for the PartTimeEmployee class.. PartTimeEmployee hourlyPay : double PartTimeEmployee(String, String, double) setHourlyPay(double) getHourlyPay() :double calculateWeeklyPay(int) :double
16
public class PartTimeEmployee extends Employee { private double hourlyPay; public PartTimeEmployee(String numberIn, String nameIn, double hourlyPayIn) { hourlyPay = hourlyPayIn; } public double getHourlyPay() { return hourlyPay; } public void setHourlyPay(double hourlyPayIn) { hourlyPay = hourlyPayIn; } public double calculateWeeklyPay(int noOfHoursIn) { return noOfHoursIn * hourlyPay; } } super( ); numberIn, nameIn Call to ‘super’ must be first instruction here
17
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(); emp = new PartTimeEmployee(number, name, pay); System.out.print("Hours worked this week? "); hours = EasyScanner.nextInt(); System.out.println(); System.out.println(emp.getName()); System.out.println(emp.getNumber()); System.out.println(emp.calculateWeeklyPay(hours)); } }
18
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
19
Employee Number? Walter Wallcarpeting A103456 310.0 Employee's Name? Hourly Pay? Hours worked this week? A103456 Walter Wallcarpeting 15.50 20
20
Extending the Oblong class…
21
6.5 9.2 Oblong myOblong; myOblong ********* ********* ********* ********* ********* ********* ExtendedOblong myOblong; = new ExtendedOblong(6.5, 9.2,‘*’); = new Oblong(6.5, 9.2);
22
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
23
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 } }
24
The new-line character..
25
for (int i = 1; i <= height; i++) { } **** ************ <NEW LINE><NEW LINE> ‘\n’ for (int j = 1; j <= length; j++) { s = s + symbol; } s = s + '\n'; <NEW LINE>
26
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) type casting What’s wrong here?
27
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 ********** ********** ********** ********** ********** ++++++++++ ++++++++++ ++++++++++ ++++++++++ ++++++++++
28
method overriding..
29
ClassAClassB
30
ClassAClassB
31
ClassAClassB method overloading
32
ClassAClassB
33
ClassAClassB method overriding
34
Customer name : String totalMoneyPaid : double totalGoodsReceived : double Customer (String, double) Customer(String) getName() : String getTotalMoneyPaid() : double getTotalGoodsReceived() : double calculateBalance() : double recordPayment(double) dispatchGoods(double) : boolean
35
Customer name : String totalMoneyPaid : double totalGoodsReceived : double Customer (String, double) Customer(String) getName() : String getTotalMoneyPaid() : double getTotalGoodsReceived() : double calculateBalance() : double recordPayment(double) dispatchGoods(double) : boolean Method overloading
36
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
37
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
38
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 method overriding
39
Customer name : String totalMoneyPaid : double totalGoodsReceived : double Customer(String) getName() : String getTotalMoneyPaid() : double getTotalGoodsReceived() : double calculateBalance() : double recordPayment(double) dispatchGoods(double) : boolean Code for the Customer class..
40
public class Customer { protected String name; } protected attributes are similar to private attributes except that they are also visible to subclasses.
41
public class Customer { protected String name; protected double totalMoneyPaid; protected double totalGoodsReceived; public Customer(String nameIn) { name = nameIn; totalMoneyPaid = 0; totalGoodsReceived = 0; } }
42
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 }
43
public boolean dispatchGoods(double goodsIn) { if(calculateBalance() >= goodsIn) { totalGoodsReceived = totalGoodsReceived + goodsIn; return true; } else { return false; } }
44
Code for the GoldCustomer class.. GoldCustomer creditLimit : double GoldCustomer(String, double) getCreditLimit() : double setCreditLimit(double) dispatchGoods(double) : boolean
45
public class GoldCustomer extends Customer { private double creditLimit; public GoldCustomer(String nameIn, double limitIn) { name = nameIn; totalMoneyPaid = 0; totalGoodsReceived = 0; creditLimit = limitIn; } }
46
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 }
47
public boolean dispatchGoods(double goodsIn) { if((calculateBalance() + creditLimit) >= goodsIn) { totalGoodsReceived = totalGoodsReceived + goodsIn; return true; } else { return false; } }
48
Calling overridden methods..
49
Customer firstCustomer; firstCustomer = new Customer("Jones"); GoldCustomer secondCustomer; secondCustomer = new GoldCustomer("Cohen", 500); // more code here firstCustomer.dispatchGoods(98.76);
50
Customer firstCustomer; firstCustomer = new Customer("Jones"); GoldCustomer secondCustomer; secondCustomer = new GoldCustomer("Cohen", 500); // more code here firstCustomer.dispatchGoods(98.76); Will call dispatchGoods from the Customer class
51
Customer firstCustomer; firstCustomer = new Customer("Jones"); GoldCustomer secondCustomer; secondCustomer = new GoldCustomer("Cohen", 500); // more code here firstCustomer.dispatchGoods(98.76); secondCustomer.dispatchGoods(32.44);
52
Customer firstCustomer; firstCustomer = new Customer("Jones"); GoldCustomer secondCustomer; secondCustomer = new GoldCustomer("Cohen", 500); // more code here firstCustomer.dispatchGoods(98.76); secondCustomer.dispatchGoods(32.44); Will call dispatchGoods from the GoldCustomer class
53
Abstract classes and methods…
54
draw() abstract draw() draw() ShapeCircleTriangle abstract Shape We will never need to create Shape objects What if we definitely want to be able to draw shapes like Circle and Triangle? abstract methods must be overridden in subclasses
55
Abstract classes and methods: An example
56
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 This class can be declared abstract This method needs to be declared abstract
57
public abstract class Employee { // attributes as before // methods as before abstract public String getStatus(); }
58
public class PartTimeEmployee extends Employee { // code as before public String getStatus() { return "Part-Time"; } }
59
public class FullTimeEmployee extends Employee { // code as before public String getStatus() { return “Full-Time"; } }
60
Inheritance and Types …
61
Shape Circle 3DCircle Circle is a kind of Shape 3DCircle is a kind of Circle 3DCircle is a kind of Shape c1 = new Circle ( ); c3d = new 3DCircle ( ); Circle Shape 3DCircle Object type Circle Object type
62
getStatus() abstract getStatus() getStatus() Employee PartTimeEmployee FullTimeEmployee public class StatusTester { public static void tester(Employee employeeIn) { System.out.println(employeeIn.getStatus()); } }
63
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
64
The Object class….
65
Employee PartTimeEmployee FullTimeEmployee String BankAccount Object
66
Generic Arrays
67
myList = new [100];Student[ ]Student This array can just store Student objects.
68
myList = new [100];BankAccount[ ] BankAccount This array can just store BankAccount objects.
69
myList = new [100]; Object[ ] Object This array can store any objects.
70
Adding items into a generic array..
71
list [0] =new Oblong ( 8.2, 13.5); Adding an Oblong object into the first position of array. Object[ ] list = new Object [100];
72
list [1] = new BankAccount (“031”, “F Torres”); Adding a BankAccount object into the second position of array.
73
Retrieving items from a generic array..
74
Object[ ] list = new Object [100]; list [1] = new BankAccount(“031, “F Torres”); Withdrawing £250 from the BankAccount object. list [1] Something wrong here Compiler regards all items in array as type Object, not type BankAccount. This is a BankAccount method.withdraw (250);
75
Object[ ] list = new Object [100]; list [1] = new BankAccount(“031, “F Torres”); list [1] But we know the second item in the array is actually of type BankAccount..withdraw (250); Withdrawing £250 from the BankAccount object.
76
How do we tell the compiler that the second item in the array is of type BankAccount ?
77
Use the technique of type-casting!
78
list [1].withdraw (250); Object[ ] list = new Object [100]; list [1] = new BankAccount(“031, “F Torres”); Withdrawing £250 from the BankAccount object.
79
(BankAccount) list [1].withdraw(250); This is how we type-cast. Object[ ] list = new Object [100]; list [1] = new BankAccount(“031, “F Torres”); Withdrawing £250 from the BankAccount object.
80
(BankAccount) list [1].withdraw(250); No we can use BankAccount methods Object[ ] list = new Object [100]; list [1] = new BankAccount(“031, “F Torres”); Withdrawing £250 from the BankAccount object.
81
How could you use an array of Objects to store items of type int, double or a char?
82
Use a wrapper class!
83
Object Integer hidden int Integer(int) getValue():int Character hidden char Character(char) getValue():char Double hidden double Double(double) getValue():double Wrapper classes
84
Autoboxing…
85
Object[] list = new Object[100]; list[0] = new Integer(37); Java 5.0 allows us to make use of a technique known as autoboxing: list[0] = 37;
86
Unboxing…
87
Integer intObject = (Integer) list[0]; int x = intObject.getValue(); Java 5.0 allows us to make use of a technique known as unboxing: int x = (Integer) list[0];
88
Practical Work
89
Vehicle regNo : String make : String year : int value : double Vehicle(String, String, int, double) getRegNo() : String getMake() : String getYear() : int getValue() : double setValue(double) calculateAge(int) : int SecondHandVehicle numberOfOwners : int SecondHandVehicle(String, String, int, double, int) getNumberOfOwners() : int hasMultipleOwners() : boolean
90
Vehicle regNo : String make : String year : int value : double Vehicle(String, String, int, double) getRegNo() : String getMake() : String getYear() : int getValue() : double setValue(double) calculateAge(int) : int Lets implement the highlighted parts of the Vehicle class.
91
Vehicle regNo : String make : String year : int value : double Vehicle(String, String, int, double) getRegNo() : String getMake() : String getYear() : int getValue() : double setValue(double) calculateAge(int) : int public class Vehicle { private String regNo; private String make; private int year; private double value; public Vehicle(String rIn, String mIn, int yIn, double vIn) { regNo = rIn; make = mIn; year = yIn; value = vIn; } }
92
Lets implement the highlighted parts of the SecondHandVehicle class. SecondHandVehicle numberOfOwners : int SecondHandVehicle(String, String, int, double, int) getNumberOfOwners() : int hasMultipleOwners() : boolean Vehicle
93
SecondHandVehicle numberOfOwners : int SecondHandVehicle(String, String, int, double, int) getNumberOfOwners() : int hasMultipleOwners() : boolean Vehicle public class SecondHandVehicle extends Vehicle { private int numberOfOwners; public SecondHandVehicle(String rIn, String mIn, int yIn, double vIn, int nIn) { super (rIn, mIn, yIn, vIn); numberOfOwners = nIn; } }
94
Once you have completed these classes remember to create a third tester class.
95
This class should generate a SecondHandVehicle object and then call its methods.
96
public class TesterProgram { public static void main (String[ ] args) { // generate at least 1 SecondHandVehicle object // test the object by calling its methods }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.