1
IM103 Wk 7 (C&K ch14, p323)
Abstraction, inheritance and interfaces
Learning objectives
By the end of this lecture you should be able to:
explain the terms abstraction and abstract data type; distinguish between method overloading and method overriding; explain the difference between dynamic (run-time) binding and static
(compile-time) binding; create your own interfaces in Java; make use of adapters in programs; explain the purpose of the toString method.
2
Abstraction
The idea of focusing on what an object does, without worrying about the detail of how it does it.
• the more abstract our specification, the more likely we are to build a system that is flexible and maintainable;
• this is because we do not tie ourselves down to one particular design.
3
Oblong
length : real numberheight : real number
calculateArea() : real numbercalculatePerimeter() : real number
• at the specification stage we don’t concern ourselves with unnecessary detail, and we don't use types that are specific to one particular programming language.
Reminder: specification of the Oblong class
4
Abstract Data Types
• a class template is often referred to as an abstract data type;• all that is available to the user of such a type is the method
descriptions (inputs and output);• in object-oriented programming languages the the principal
data types are abstract data types (objects of a class).
More on inheritance and polymorphism
Reminder:the Employee hierarchy
Employee
number : Stringname : String
Employee(String, String)getNumber() : StringgetName() : StringgetStatus() : String
FullTimeEmployeeannualSalary : double
FullTimeEmployee(String, String, double)setAnnualSalary(double)getAnnualSalary() : doublecalculateMonthlyPay () : doublegetStatus() : String
PartTimeEmployeehourlyPay : double
PartTimeEmployee(String,String, double)setHourlyPay(double)getHourlyPay() : doublecalculateWeeklyPay(int) : doublegetStatus() : String
6
Reminder of the getStatus method
• was declared as an abstract method in the superclass (the Employee class)
• was overridden in the subclasses (FullTimeEmployee and PartTimeEmployee).
• calling this method causes a String to be returned:
• "Full-Time" for a FullTimeEmployee object;• "Part-Time" for a PartTimeEmployee object.
7
Third item
Second item
First item
Part-timeemployee
Full-timeemployee
Full-timeemployee
An array holding items of different types
• Program 14.1 creates an array like this.
8
Analysis of program 14.1
An array is declared, big enough for three employees:
Employee[] employeeList = new Employee[3];
Local variables ared declared to hold values entered by the user:
String num, name; double pay; char status;
for(int i = 0; i < employeeList.length; i++){ System.out.print("Enter the employee number: "); num = EasyIn.getString(); System.out.print("Enter the employee's name: "); name = EasyIn.getString(); System.out.print("<F>ull-time or <P>art-time? "); status = EasyIn.getChar(); if(status == 'f' || status == 'F') { System.out.print("Enter the annual salary: "); } else { System.out.print("Enter the hourly pay: "); } pay = EasyIn.getDouble();
........................
A for loop is used to get details of the three employees:
10
•The for loop continues;• we create the new employee, either full-time or part-time:
........................
if(status == 'f' || status == 'F') { employeeList[i] = new FullTimeEmployee(num, name, pay); } else { employeeList[i] = new PartTimeEmployee(num, name, pay); } System.out.println();}
11
for(int i = 0; i < employeeList.length; i++){ System.out.println("Employee number: " + employeeList[i].getNumber()); System.out.println("Employee name: " + employeeList[i].getName()); System.out.println("Status: " + employeeList[i].getStatus()); System.out.println();}
• we display the details of each employee
• the correct status is displayed, even the status of the employee was not known until run-time.
12
Enter the employee number: 1Enter the employee's name: Jones<F>ull-time or <P>art-time? fEnter the annual salary: 30000
Enter the employee number: 2Enter the employee's name: Agdeboye<F>ull-time or <P>art-time? fEnter the annual salary: 35000
Enter the employee number: 3Enter the employee's name: Sharma<F>ull-time or <P>art-time? pEnter the hourly pay: 15
Employee number: 1Employee name: JonesStatus: Full-Time
Employee number: 2Employee name: AgdeboyeStatus: Full-Time
Employee number: 3Employee name: SharmaStatus: Part-Time
Sample Output
13
Run-time binding vs compile-time binding
• the technique that makes the above program possible is known as run-time binding or dynamic binding;
• if the language used compile-time (static) binding, then when the code for a class was compiled, the code for each of its methods would be compiled alongside it;
• every time an object received a message to invoke that method, the control of the program would jump to the place where the code for the method was stored;
• the instructions in that method would then be executed, and the program control would then return to the place where it left off.
14
• in the MixedListTester we don't know until run-time what sort of object we are dealing with.
• where should the program jump to in the following line?
System.out.println("Status: " + employeeList[i].getStatus());
• this decision must be made at run-time;• when a new object is created, it must hold information about
where its methods are stored; • thus, the decision about which actual method is called can be
postponed until run-time;• this technique is called run-time binding.
Run-time binding vs compile-time binding ... continued
15
• Java normally uses dynamic (run-time) binding;
• however, dynamic binding involves more processing and more storage space than static binding;
• if we know that a method is not going to be overridden we can use the final modifier with a method;
• this means that the method cannot be overridden;
• if we make the method final, then static binding will be used.
Using the final modifier with methods
16
• both method overriding and method overloading are forms of polymorphism;
• overriding involves redefining a superclass method in a subclass;
• overloading means having many methods with the same name, each with a different parameter list.
Overriding vs Overloading (Reminder)
17
Abstract classes and interfaces
• an interface is a class in which all methods are abstract;• examples that we have used are
ActionListener and MouseListener;• we can also write our own interfaces.
18
Developing our own interface
• we wish to produce a re-usable class to which we could attach a logo of our choice;
• to make a class attachable, we need to provide an attach method;
• to ensure that a class has an attach method we can develop Attachable interface.
19
The attachable interface
import java.awt.*;
interface Attachable{ public void attach(Component c, int xPos, int yPos);}
20
• the interface has a single abstract method, attach;• we do not have to use the abstract modifier because
all interface methods are abstract by definition;• a class that implements Attachable, will become a
kind of Attachable, and will "inherit" and redefine the attach method.
Notes on the Attachable interface
21
import java.awt.*;
class CAndKLogo implements Attachable{ public void attach(Component c, int xPos, int yPos) { Graphics g = c.getGraphics(); g.setFont(new Font("Serif", Font.BOLD,15)); g.setColor(Color.red); g.fillRect(xPos,yPos,125,20); g.setColor(Color.yellow); g.drawString("Charatan & Kans",xPos + 3, yPos + 15); }}
Using the Attachable interface
22
Notes on the CAndKlogo class
• the first line gets the graphics context - that is, it creates a Graphics object associated with this component:
Graphics g = c.getGraphics();
• the next line sets the font to one of our own creation:
g.setFont(new Font("Serif", Font.BOLD,15));
• this logo, or any other Attachable, can be attached to a graphical component such as a Panel;
• this is done in the LogoPanel class.
The LogoPanel classimport java.awt.*;
class LogoPanel extends Panel{ private Attachable logo; private int xPos; private int yPos;
public LogoPanel(Attachable logoIn, int xIn, int yIn) { logo = logoIn; xPos = xIn; yPos = yIn; }
public void paint(Graphics g) { logo.attach(this, xPos, yPos); }}
24
public class LogoTester{ public static void main(String[] args) { EasyFrame f = new EasyFrame(); CAndKLogo logo = new CAndKLogo(); LogoPanel loPanel = new LogoPanel(logo, 10, 5); f.add(loPanel); f.setSize(250,250); f.setLocation(200,200); f.setVisible(true); }}
Adding the LogoPanel to a frame
25
Running the LogoTester
26
Analysis of the EasyFrame class
import java.awt.*;import java.awt.event.*;
// uses the WindowListener Interfacepublic class EasyFrame extends Frame implements WindowListener{
// constructors public EasyFrame()
{addWindowListener(this);
} // provides a title for the frame public EasyFrame(String msg) {
super(msg); addWindowListener(this);
}…………………………………………………………………………………
27
………………………………………………………………………………………
/* the frame is disposed of when the cursor is clicked on the crosshairs */ public void windowClosing(WindowEvent e) {
dispose(); // disposes of the frame }
// when the window closes the program is shut down public void windowClosed(WindowEvent e) { System.exit(0); // ends the program }
………………………………………………………………………………………
Analysis of the EasyFrame class … continued
……………………………………………………………………………… /* the remaining methods are required by the WindowListenrer interface */ public void windowDeactivated(WindowEvent e) { }
public void windowActivated(WindowEvent e) { }
public void windowDeiconified(WindowEvent e) { }
public void windowIconified(WindowEvent e) { }
public void windowOpened(WindowEvent e) { }
}
Analysis of the EasyFrame class … continued
29
• using an interface means that we have to code all the interface methods, even those we are not interested in;
• as an alternative we can use an adapter;• an adapter acts as an intermediary between our class and the
interface, making it unnecessary to code all the methods; • an adapter is provided for every interface that comes with
the standard Java packages.
Adapters
30
• an adapter has to be inherited;• our EasyFrame class can't inherit the adapter as it already
inherits Frame;• we will have to write a new class to add to a Frame later on - we
will call it EasyListener.
Creating a closing frame using an adapter
The EasyListener classimport java.awt.*;import java.awt.event.*; class EasyListener extends WindowAdapter{ public void windowClosing(WindowEvent e) { // determine which window caused the event Window win = e.getWindow(); // dispose of that window win.dispose(); } public void windowClosed(WindowEvent e) { // close down the whole system System.exit(0); }}
32
Using the EasyListener class
// this just produces an empty frameimport java.awt.event.*;import java.awt.*;
public class RunChangingFace2{ public static void main(String[] args) {
Frame frame = new Frame(); frame.setSize(250,200); // add an EasyListener to the frame frame.addWindowListener(new EasyListener()); frame.setVisible(true); }}
import java.awt.event.*;import java.awt.*;
public class RunChangingFace3{ public static void main(String[] args) { class EasyListener extends WindowAdapter // an inner class { public void windowClosing(WindowEvent e) { Window win = e.getWindow(); win.dispose(); } public void windowClosed(WindowEvent e) { System.exit(0); } } Frame frame = new Frame(); frame.setSize(250,200); frame.addWindowListener(new EasyListener()); frame.setVisible(true); }}
Using an inner class
34
ReminderEvery class is inherited from a "super superclass" called Object.
• the Object class has a method called toString that returns a String, and that can be overridden by subclasses of Object;
• methods of other classes can be set up to use this method;• some classes in the standard Java packages have methods (for
example print and println) which take an Object object as a parameter and use its toString method.
The toString method
35
Overriding the toString method in the BankAccount class
public String toString(){ return "Account Number: " + accountNumber + "\nAccount Name: " + accountName + "\nCurrent Balance: " + balance + "\n";}
36
Using the toString method
public class RunAccount{ public static void main(String[] args) { BankAccount account1 = new BankAccount("001", "Sarah Patel"); BankAccount account2 = new BankAccount("002", "Robinder Grewel"); System.out.println(account1); System.out.println(account2); EasyIn.pause(); }}
37
Output
Account Number: 001Account Name: Sarah PatelCurrent Balance: 0.0
Account Number: 002Account Name: Robinder GrewelCurrent Balance: 0.0
• This works because there is a version of println that accepts an object and outputs the return value of its toString method.
38
• We will create a class called EasyText which extends the TextArea class, giving it a display method.
The EasyText class
import java.awt.*; class EasyText extends TextArea { public void display(Object objectIn)
{ //call the setText method of the superclass super.setText(objectIn.toString()); } }
import java.awt.*;
public class EasyTextTester{ public static void main(String[] args) { EasyFrame frame = new EasyFrame(); BankAccount account = new BankAccount("001", "Bill Tin-Wardrobe"); EasyText eText = new EasyText(); frame.setSize(300,170); frame.setBackground(Color.lightGray); frame.add(eText); frame.setVisible(true); eText.display(account); }}
Using the EasyText class with the BankAccount class
40
Result of using the display method of EasyText
Recommended