1 im103 wk 7 (c&k ch14, p323) abstraction, inheritance and interfaces learning objectives by the...

40
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

Upload: britney-jacobs

Post on 17-Jan-2018

214 views

Category:

Documents


0 download

DESCRIPTION

3 Oblong length : real number height : real number calculateArea() : real number calculatePerimeter() : 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

TRANSCRIPT

Page 1: 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

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.

Page 2: 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

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.

Page 3: 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

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

Page 4: 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

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).

Page 5: 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

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

Page 6: 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

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.

Page 7: 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

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.

Page 8: 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

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;

Page 9: 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

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:

Page 10: 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

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();}

Page 11: 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

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.

Page 12: 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

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

Page 13: 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

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.

Page 14: 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

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

Page 15: 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

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

Page 16: 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

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)

Page 17: 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

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.

Page 18: 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

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.

Page 19: 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

19

The attachable interface

import java.awt.*;

interface Attachable{ public void attach(Component c, int xPos, int yPos);}

Page 20: 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

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

Page 21: 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

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

Page 22: 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

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.

Page 23: 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

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); }}

Page 24: 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

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

Page 25: 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

25

Running the LogoTester

Page 26: 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

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);

}…………………………………………………………………………………

Page 27: 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

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

Page 28: 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

……………………………………………………………………………… /* 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

Page 29: 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

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

Page 30: 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

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

Page 31: 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

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); }}

Page 32: 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

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); }}

Page 33: 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

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

Page 34: 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

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

Page 35: 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

35

Overriding the toString method in the BankAccount class

public String toString(){ return "Account Number: " + accountNumber + "\nAccount Name: " + accountName + "\nCurrent Balance: " + balance + "\n";}

Page 36: 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

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(); }}

Page 37: 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

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.

Page 38: 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

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()); } }

Page 39: 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

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

Page 40: 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

40

Result of using the display method of EasyText