About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State.

Similar documents
About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at Interfaces.

DCS235 Software Engineering Exercise Sheet 2: Introducing GUI Programming

ITI Introduction to Computing II

8. Polymorphism and Inheritance

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

Computer Science 210: Data Structures

ITI Introduction to Computing II

Object Oriented Modeling

Object-Oriented Concepts and Design Principles

Class, Variable, Constructor, Object, Method Questions

First Name: AITI 2004: Exam 2 July 19, 2004

Java Object Oriented Design. CSC207 Fall 2014

B2.52-R3: INTRODUCTION TO OBJECT ORIENTATED PROGRAMMING THROUGH JAVA

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

First Name: AITI 2004: Exam 2 July 19, 2004

PROGRAMMING LANGUAGE 2

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

CSC 1214: Object-Oriented Programming

CSC 102 Lecture Notes Week 1 Introduction to the Course Introduction to Jav a

Classes and Objects 3/28/2017. How can multiple methods within a Java class read and write the same variable?

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects

Instance Members and Static Members

C18a: Abstract Class and Method

Zhifu Pei CSCI5448 Spring 2011 Prof. Kenneth M. Anderson

MIT AITI Swing Event Model Lecture 17

index.pdf January 21,

SINGLE EVENT HANDLING

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

2. (True/False) All methods in an interface must be declared public.

Final Exam CS 251, Intermediate Programming December 10, 2014

1.00 Lecture 8. Using An Existing Class, cont.

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

ITI Introduction to Computing II

ITI Introduction to Computing II

Final Exam CS 251, Intermediate Programming December 13, 2017

CSC 102 Lecture Notes Week 2 Introduction to Incremental Development and Systematic Testing More Jav a Basics

Course Supervisor: Dr. Humera Tariq Hands on Lab Sessions: Ms. Sanya Yousuf

Inheritance and Interfaces

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

COMP 110/L Lecture 19. Kyle Dewey

About This Lecture. Container Traversal. Container Traversal. Outline. Array Traversal. List Traversal inside the List class

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

What will this print?

For this section, we will implement a class with only non-static features, that represents a rectangle

Keyword this. Can be used by any object to refer to itself in any class method Typically used to

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

1 Getting started with Processing

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Object Oriented Programming 2015/16. Final Exam June 28, 2016

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

CS260 Intro to Java & Android 03.Java Language Basics

AP CS Unit 11: Graphics and Events

C++ Important Questions with Answers

Page 1 of 16. Proctors are unable to respond to queries about the interpretation of exam questions. Do your best to answer exam questions as written.

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

Object-Oriented Programming: Revision. Revision / Graphics / Subversion. Ewan Klein. Inf1 :: 2008/09

Programming Languages and Techniques (CIS120)

Graphical User Interface (GUI)

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

CSCE3193: Programming Paradigms

CSC 160 LAB 8-1 DIGITAL PICTURE FRAME. 1. Introduction

3.1 Class Declaration

Chapter 6: Inheritance

Chapter 9 Inheritance

Final Exam 90 minutes Eng. Mohammed S. F. Abdual Al

The Essence of OOP using Java, Nested Top-Level Classes. Preface

Object Oriented Programming. Java-Lecture 11 Polymorphism

CS111: PROGRAMMING LANGUAGE II

Programming overview

Classes as Blueprints: How to Define New Types of Objects

Systems Programming. Bachelor in Telecommunication Technology Engineering Bachelor in Communication System Engineering Carlos III University of Madrid

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

CS180 Recitation. More about Objects and Methods

Inheritance, Polymorphism, and Interfaces

Object-Oriented Concepts

Object-oriented programming in Java (2)

Outline. Object-Oriented Design Principles. Object-Oriented Design Goals. What a Subclass Inherits from Its Superclass?

Arrays Classes & Methods, Inheritance

GUI Event Handlers (Part I)

CS111: PROGRAMMING LANGUAGE II

Industrial Programming

What is an Object. Industrial Programming. What is a Class (cont'd) What is a Class. Lecture 4: C# Objects & Classes

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed

JAVA: A Primer. By: Amrita Rajagopal

CS-202 Introduction to Object Oriented Programming

Java Magistère BFA

1 Getting started with Processing

CS/ENGRD 2110 SPRING Lecture 2: Objects and classes in Java

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof

CS-140 Fall 2017 Test 2 Version A Nov. 29, 2017

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

CSE 70 Final Exam Fall 2009

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Chapter 14 Abstract Classes and Interfaces

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Building custom components IAT351

Transcription:

Revised 01/09/05 About This Lecture Slide # 2 Data Abstraction - Interfaces and Implementations In this lecture we will learn how Java objects and classes can be used to build abstract data types. CMPUT 115 - Lecture 2 Department of Computing Science University of Alberta \ Some code in this lecture is based on code from the book: Java Structures by Duane A. Bailey or the companion structure package Slide # 3 Slide # 4 Outline Object Concepts Interface Use Implementation Java interfaces Object Concepts An object has: a private state A set of resources that it provides. Let s call this its public protocol Each object is an instance of a class. The class defines the public protocol, so all objects of a class have the same protocol. The state of an object differentiates it from other objects in the same class. Slide # 5 Slide # 6 Object Class, Protocol and State Public protocol external request private private state private state private state public interface state public public interface interface public protocol class In Java, the public protocol of a class includes: The name of the superclass Public variable declarations Public constructor declarations Public message declarations Public static method declarations 1

Slide # 7 Slide # 8 Example: Point Class Even before you knew how to write your own classes in CMPUT 114, you could create objects from classes that other people had written You relied on documentation to tell you about the publicly-accessible resources in a class Example - using the Point class in awt package: http://www-csfy.cs.ualberta.ca/~c114/jdk1.2.2/docs/api/java/awt/point.html Interface, Implementation & Use There are three aspects for any class: Protocol: a description of the resources that the class provides. Implementation: the code that describes the private state of instances and implements the computational resources of the class. Use: code in a using class causes new instances of the used class to be created and invokes computations on these instances. We will now investigate these 3 aspects in relation to the Ratio class Protocol - Ratio Class (slide 1) public class Ratio { /* an object for storing a fraction */ public Ratio(int top, int bottom) /* a constructor used to construct a new object */ public int getnumerator() /* post: return the numerator of the fraction */ Slide # 9 Protocol - Ratio Class (slide 2) Slide # 10 public double value() /* post: returns the real value equivalent to ratio */ public Ratio add(ratio other) /* pre: other is non-null post: return new fraction - the sum of this and other */ public int getdenominator() /* post: return the denominator of the fraction */ Slide # 11 Slide # 12 Using classes What can we do with a class once we ve defined it how can we use it? In Java, class A can use class B by: Creating instances of class B. Sending messages to instances of class B. Invoking static methods from class B. Using variables that are declared in class B. Using message arguments that are declared to be of class B. Using the Ratio Class public class SomeClass { public static void main(string[] args) { Ratio r1; Ratio r2; Ratio r3; r1 = new Ratio(3,5); // r1 == 3/5 (0.6) r2 = new Ratio(1,4); // r2 == 1/4 (0.25) r3 = r1.add(r2); // r1 still 3/5, r2 still 1/4 // r3 == 17/20 (0.85) r1 = r1.add(r2); // r1 == 17/20 System.out.println(r1.value()); // 0.85 printed 2

Slide # 13 Slide # 14 Implementation In Java, a class implementation includes: Bindings for static variables Declarations of instance variables Static method code Constructor code Instance method code (to handle messages) Implementation - Ratio Class (slide 1) public class Ratio { /* an object for storing a fraction */ protected int numerator; // numerator of ratio protected int denominator; // denominator of ratio public Ratio(int top, int bottom) { /* pre: bottom!= 0 post: constructs a ratio equivalent to top/bottom */ this.numerator = top; this.denominator = bottom; Slide # 15 Slide # 16 Implementation - Ratio Class -2 public int getnumerator() { /* post: return the numerator of the fraction */ return this.numerator; public int getdenominator() { /* post: return the denominator of the fraction */ return this.denominator; Implementation - Ratio Class -3 public double value() { /* post: returns the real value equivalent to ratio */ return (double)this.numerator /(double)this.denominator; public Ratio add(ratio other) { /* pre: other is non-null post: return new fraction - the sum of this and other */ return new Ratio(this.numerator*other.denominator+ this.denominator*other.numerator, this.denominator*other.denominator); Slide # 17 Slide # 18 Java Interfaces For many classes, the protocol and the implementation are in the same file. However, Java has a specific feature called an Interface that can be used to separate the protocol of a class from its implementation Unfortunately, interfaces are not always used! A Java interface contains no code, only message signatures. Benefits of Using Interfaces Java does not allow multiple inheritance: interfaces address this issue Interfaces exploit the concept of type conformance: a type can conform to another if it has the same set of methods (and maybe some extras) These two types don t have to be related by inheritance more freedom! Interfaces allow a class to specify that its instances can be used anywhere that a matching interface is required 3

Slide # 19 Slide # 20 Inheritance versus interfaces Inheritance: a subclass shares a common structure and behaviour with its superclass Example Interface - IntRectangle We will now learn how to write and implement an interface. Interface: classes that implement an interface share common behaviours (but not structure) We will write: IntRectangle (the interface) IntRectangleI class (implements IntRectangle interface) IntRectangleP class (implements IntRectangle interface) Java Interface - IntRectangle Slide # 21 Implementing Java Interfaces Slide # 22 public interface IntRectangle { public Point origin(); /* post: returns the Point at the upper left. */ public Point corner(); /* post: returns the Point at the lower right. */ public int height(); /* post: returns the size in the vertical direction. */ public int width(); /* post: returns size in the horizontal direction. */ A Java class is used to implement a Java Interface. The class must provide code for every message in the Java Interface. The class name must be different from the Java Interface name. Slide # 23 Slide # 24 Class - IntRectangleP (slide 1) Class - IntRectangleP (slide 2) public class IntRectangleP implements IntRectangle { protected Point origin; // upper left protected Point corner; // lower right public IntRectangleP (Point startpoint, Point endpoint){ /* post: constructs an IntRectangleP with the given upper left and lower right Points. */ this.origin = startpoint; this.corner = endpoint; public IntRectangleP (int x, int y, int width, int height) { /* post: constructs an IntRectangleP whose upper left point has the given x and y coordinates, the given width in the x direction and the given height in the y direction. */ this.origin = new Point(x, y); this.corner = new Point(x + width, y + height); public Point origin() { /* post: returns the Point at the upper left. */ return this.origin; 4

Class - IntRectangleP (slide 3) public Point corner() { /* post: returns the Point at the lower right. */ return this.corner; public int height() { /* post: returns the size in the vertical direction. */ return (this.corner.y - this.origin.y); public int width() { /* post: returns size in the horizontal direction. */ Slide # 25 Slide # 26 Multiple Classes can Implement a Java Interface We can have an arbitrary number of classes that implement the same interface For example, we could have another class that implements the IntRectangle interface, named the IntRectangleI class. return (this.corner.x - this.origin.x); Slide # 27 Slide # 28 Class - IntRectangleI (slide 1) public class IntRectangleI implements IntRectangle { protected int x; // x coord of upper left protected int y; // y coord of upper left protected int width; // size in x direction; protected int height; // size in y direction; public IntRectangleI (Point startpoint, Point endpoint) { /* post: constructs an IntRectangleI with the given upper left and lower right Points. */ this.x = startpoint.x; this.y = startpoint.y; this.width = endpoint.x - this.x; this.height = endpoint.y - this.y; Class - IntRectangleI (slide 2) public IntRectangleI (int x, int y, int width, int height) { /* post: constructs an IntRectangleI whose upper left point has the given x and y coordinates, the given width in the x direction and the given height in the y direction. */ this.x = x; this.y = y; this.width = width; this.height = height; public Point origin() { /* post: returns the Point at the upper left. */ return new Point(this.x, this.y); Class - IntRectangleI (slide 3) public Point corner() { /* post: returns the Point at the lower right. */ return new Point(this.x + this.width, this.y + this.height); public int height() { /* post: returns the size in the vertical direction. */ return this.height; public int width() { /* post: returns size in the horizontal direction. */ return this.width; Slide # 29 Slide # 30 Declaring Variables using Interfaces We can declare variables to be the Interface type, but must create instances of the implementation classes to bind them to. Can t instantiate an interface! Parameters can also be declared to be an Interface type, allowing us to write methods that work for instances of different classes. 5

` ` ` ` _ Slide # 31 Slide # 32 Using IntRectangle Generic method to compute area Public class EgClass { public void main(string args[]) { IntRectangle rectangle; rectangle = new IntRectangleP(new Point(3, 4), new Point(5, 9)); System.out.println(EgClass.area(rectangle)) ; rectangle = new IntRectangleI(3, 4, 2, 5); System.out.println(EgClass.area(rectangle)) ; public static int area(intrectangle r) { /* post: returns the rectangle s area. */ return r.width() * r.height(); r might be bound to an instance of IntRectangleP or to an instance of InRectangleI. Another Example of an Interface Slide # 33 actionperformed( ) Slide # 34 In CMPUT 114 you wrote applets that contained buttons (or other Components), which the user could click on Your applet had a signature like this:! " # $ %& ' ( %) *,+ Only need this last part if your applet is to respond to user s actions (e.g. mouse click, click on button, enter text in text field etc.) The ActionListener interface dictates that every implementing class defines an actionperformed() method if not defined, compiler gives us an error message For example, in class MyClass: -,.0/2143 5"6$7398;:<5 =>3 72? @<A$B%C)7BEDFA<8G&Ḧ 5=E3 7?I 6$A$?,=JA<K L MNMNMO<O0P Q$R,S;TVU2W2T2XSW,PTZY;T&Q[TVUS\W,P<TV]ZQ<^MZMNM Slide # 35 Slide # 36 How it works For more information When the user clicks a button, the button's action listeners are notified. See the following: 1. http://java.sun.com/docs/books/tutorial/uiswing/over view/event.html The button creates an ActionEvent object, reference is passed to listener. This causes the action listener's actionperformed() method to be invoked 2. http://wwwcsfy.cs.ualberta.ca/~c114/jdk1.2.2/docs/api/java/awt/ event/actionlistener.html ActionEvent object contains all information about the event that has occurred you write code that extracts that information and determines what should happen in response to event 3. http://wwwcsfy.cs.ualberta.ca/~c114/jdk1.2.2/docs/api/java/awt/ event/actionevent.html 6

Slide # 37 Summary: Interface definition An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy An interface defines a set of methods but does not implement them. A class that implements the interface agrees to implement all the methods defined in the interface, thereby agreeing to certain behavior Interfaces can also define constants Sun Microsystems (web site tutorial) 7