extending classes with inheritance learning objectives by the end of this lecture you should be able...
TRANSCRIPT
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.
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 is not a kind of Computer
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
superclass
subclass
base class
derived class
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));
}}
RUN
Employee Number?
Walter WallcarpetingA103456310.0
Employee's Name?
Hourly Pay?
Hours worked this week?
A103456
Walter Wallcarpeting
15.50
20
Extending the Oblong class
6.5
9.2
Oblong myOblong = new Oblong(6.5, 9.2);
******************************************************
ExtendedOblong
symbol : char
ExtendedOblong(double, double, char) setSymbol(char) draw() : String
Oblong
length : doubleheight : double
Oblong(double, double)setLength(double)setHeight(double)getLength() : doublegetHeight() : doublecalculateArea() : doublecalculatePerimeter() : double
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
************
**** **** ****<NEW LINE> <NEW LINE>‘\n’ ‘\n’
for (int j = 1; j <= length; j++){ s = s + symbol; }s = s + '\n';
for (int i = 1; i <= height; i++){ }
<NEW LINE>‘\n’
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
**************************************************
++++++++++++++++++++++++++++++++++++++++++++++++++
Method overriding
Customer
name : StringtotalMoneyPaid : doubletotalGoodsReceived : double
Customer(String)getName() : StringgetTotalMoneyPaid() : doublegetTotalGoodsReceived() : doublecalculateBalance() : doublerecordPayment(double)dispatchGoods(double) : boolean
GoldCustomer
creditLimit : double
GoldCustomer(String, double)getCreditLimit() : doublesetCreditLimit(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;
}
}
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
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
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";}
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()); }}
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-TimePart-Time
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()
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
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 myAccount = objectList.getItem(3);
System.out.println(myAccount.getBalance());
(BankAccount) objectList.getItem(3);
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.
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)) ;
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
Third item
Second item
First item
Part-timeemployee
Full-timeemployee
Full-timeemployee
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(); } }}
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