Java interface Lecture 15

Similar documents
Event Handling Java 7

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

CSE 143 Lecture 20. Circle

ITI Introduction to Computing II

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

ITI Introduction to Computing II

Making New instances of Classes

COMP 250. inheritance (cont.) interfaces abstract classes

Outline. Inheritance. Abstract Classes Interfaces. Class Extension Overriding Methods Inheritance and Constructors Polymorphism.

CS-202 Introduction to Object Oriented Programming

Upcasting. Taking an object reference and treating it as a reference to its base type is called upcasting.

Inheritance & Polymorphism Recap. Inheritance & Polymorphism 1

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Interfaces. Relatedness of types. Interface as a contract. The area and perimeter of shapes 7/15/15. Savitch ch. 8.4

Topic 7: Algebraic Data Types

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

Object Oriented Programming. Java-Lecture 11 Polymorphism

OBJECT ORİENTATİON ENCAPSULATİON

Advanced Placement Computer Science. Inheritance and Polymorphism

Java Object Oriented Design. CSC207 Fall 2014

COMP200 - Object Oriented Programming: Test One Duration - 60 minutes

Inheritance, Polymorphism, and Interfaces

Reviewing OO Concepts

Exceptions & Miscellaneous Lecture 17

8. Polymorphism and Inheritance

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

Reviewing OO Concepts

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

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

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

Polymorphism and Interfaces. CGS 3416 Spring 2018

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

Some client code. output. subtype polymorphism As dynamic binding occurs the behavior (i.e., methods) follow the objects. Squarer

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

!" #$ +-,.-% $/00&&& $ 0$0

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

Java Comparable interface

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Chapter 14 Abstract Classes and Interfaces

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

What is Polymorphism? CS 112 Introduction to Programming

Java Primer. CITS2200 Data Structures and Algorithms. Topic 0

CS2 Assignment A1S The Simple Shapes Package

Introduction to C++ Introduction to C++ Dr Alex Martin 2013 Slide 1

Chapter 21- Using Generics Case Study: Geometric Bunch. Class: Driver. package csu.matos; import java.util.arraylist; public class Driver {

Introductory Programming Inheritance, sections

CSE 8B Programming Assignments Spring Programming: You will have 5 files all should be located in a dir. named PA3:

Inheritance and Polymorphism

L4: Inheritance. Inheritance. Chapter 8 and 10 of Budd.

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017

Inheritance and Polymorphism

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

S.O.L.I.D: Software Engineering Principles

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

Inheritance and Polymorphism

Inheritance and Interfaces

CS250 Intro to CS II. Spring CS250 - Intro to CS II 1

Grouping objects Lecture 7

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

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

Objects and Classes Lecture 2

CMSC 132: Object-Oriented Programming II

Object-Oriented Programming

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

index.pdf January 21,

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

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

More sophisticated behaviour Lecture 09

ITI Introduction to Computing II

Chapter 9 - Object-Oriented Programming: Polymorphism

Inheritance, and Polymorphism.

ITI Introduction to Computing II

CHAPTER 9 INTERFACES AND POLYMORPHISM

Week 9. Abstract Classes

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Polymorphism. Agenda

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

(800) Toll Free (804) Fax Introduction to Java and Enterprise Java using Eclipse IDE Duration: 5 days

Inheritance (Deitel chapter 9)

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Programming in the Large II: Objects and Classes (Part 2)

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

Programming in C# Inheritance and Polymorphism

AShape.java Sun Jan 21 22:32: /** * Abstract strategy to compute the area of a geometrical shape. Dung X. Nguyen * * Copyright

In this lab, you will be given the implementation of the classes GeometricObject, Circle, and Rectangle, as shown in the following UML class diagram.

Inheritance. Inheritance

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

CS Week 13. Jim Williams, PhD

Design Pattern - Factory Pattern

Chapter 11 Classes Continued

Interfaces. An interface defines a set of methods. An interface declaration contains signatures, but no implementations.

CSE Programming Languages Final Exam - Autumn Answer Key

COMP 250. Lecture 29. interfaces. Nov. 18, 2016

More C++ : Vectors, Classes, Inheritance, Templates

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes

Transcription:

Lecture 15 Waterford Institute of Technology April 5, 2016 John Fitzgerald Waterford Institute of Technology, Java interface Lecture 15 1/34

Presentation outline Estimated duration presentation Questions at end presentation Topics discussed: Java 7 interface type Comparison with class Polymorphism Application in algorithm reuse Waterford Institute of Technology, Java interface Lecture 15 2/34

Device interface Simple example Consider interface design for toy shown Draw button: draw shapes. Scale button: (+) increase size. (-) decrease size. Waterford Institute of Technology, Java interface Lecture 15 3/34

Device interface Outline implementations for toy example Circle public class Circle private int radius; public Circle (int radius) this.radius = radius; public void draw () // Draw circle public void scale(int factor) radius = factor; Triangle public class Triangle private int height; private int base; public Triangle(int height, int base) this.height = height; this.base = base; public void draw () // Draw triangle public void scale(int factor) base = factor; height = factor; Waterford Institute of Technology, Java interface Lecture 15 4/34

Device interface Outline implementations for toy example Square public class Square private int side; public Square(int side) this.side = side; public void draw () // Draw square public void scale(int factor) side = factor; Pentagon public class Pentagon private int radius; public Pentagon(int radius) this.radius = radius; public void draw () // Draw pentagon public void scale(int factor) radius = factor; Waterford Institute of Technology, Java interface Lecture 15 5/34

Device interface Outline implementations for toy example Instantiate shapes Circle circle = new Circle (100); Triangle triangle = new Triangle (100, 100); Square square = new Square (100); Pentagon pentagon = new Pentagon (100); Draw Shapes circle.draw(); triangle.draw(); square.draw(); pentagon.draw(); Waterford Institute of Technology, Java interface Lecture 15 6/34

Device interface Outline implementations for toy example using Java interface type Define an interface public interface Drawable void draw(); void scale(int factor); Each shape implements Drawable, example: public class Circle implements Drawable void draw()... void scale(int factor)... Create list Drawable shapes and draw them ArrayList<Drawable> shapes = new ArrayList<>(); shapes.add(new Circle (100)); shapes.add(new Triangle (100, 100)); shapes.add(new Square (100)); shapes.add(new Pentagon (100)); for (Drawable shape : shapes) shape.draw(); Waterford Institute of Technology, Java interface Lecture 15 7/34

Device interface Outline implementations for toy example - comparison different designs Instantiate shapes Circle circle = new Circle (100); Triangle triangle = new Triangle (100, 100); Square square = new Square (100); Pentagon pentagon = new Pentagon (100); Create list Drawable shapes ArrayList<Drawable> shapes; shapes = new ArrayList<>(); shapes.add(new Circle (100)); shapes.add(new Triangle (100, 100)); shapes.add(new Square (100)); shapes.add(new Pentagon (100)); Draw Shapes circle.draw(); triangle.draw(); square.draw(); pentagon.draw(); Draw shapes for (Drawable shape : shapes) shape.draw(); Waterford Institute of Technology, Java interface Lecture 15 8/34

Description interface is a Java type that may contain only Method signatures Constant declarations Note that interface defines interfaces class defines classes Methods implemented in class that implements interface public interface Drawable public void draw(); public void scale(int x, int y); access modifier public optional Waterford Institute of Technology, Java interface Lecture 15 9/34

Compare with class Java interface different from class interface specifies behaviour only Cannot create objects of an interface Create objects of classes that implement interfaces public class Tree implements Drawable public void draw()... public void scale(int x, int y)... implementation here Waterford Institute of Technology, Java interface Lecture 15 10/34

Implementation A class may: Provide additional methods unrelated to interface Is obliged to implement all methods in interface May, optionally, provide @Override annotation to implemented methods public class Triangle implements Drawable @Override public void draw()...//must implement draw @Override public void scale(int x, int y)...//must implement scale public int getarea()...//may include additional methods Waterford Institute of Technology, Java interface Lecture 15 11/34

Implementation Many classes may implement particular interface Class states that it implements particular interface public class Triangle implements Drawable... Class provides suitable implementation of interface methods public class Triangle implements Drawable @Override public void draw()... public class House implements Drawable @Override public void draw()... Waterford Institute of Technology, Java interface Lecture 15 12/34

Converting to class Object of class implementing interface may be stored in variable whose type is the interface Tree implements Drawable Tree object reference can be stored in Drawable variable Facilitates unifying behaviour Drawable element = new Tree(...); //create array of Drawable variables Drawable[] elements = new Drawable[2]; //Assign different objects to elements in array Drawable elements[0] = new House(...); Drawable elements[1] = new Triangle(...); Waterford Institute of Technology, Java interface Lecture 15 13/34

Working without Java interfaces ArrayList<House> houses = new ArrayList<>(); houses.add(new House(100, 200)); houses.add(new House(150, 250)); for(house house : houses) house.draw(); ArrayList<Tree> trees = new ArrayList<>(); trees.add(new Tree(100, 200, 400)); trees.add(new Tree(500, 150, 250)); for(tree tree : trees) tree.draw(); Waterford Institute of Technology, Java interface Lecture 15 14/34

Working with Java interfaces ArrayList<Drawable> elements = new ArrayList<>(); elements.add(new House(100, 200)); elements.add(new House(150, 250)); elements.add(new Tree(100, 200, 400)); elements.add(new Tree(500, 150, 250)); for(drawable element : elements) element.draw(); House and Tree class must both implement Drawable interface. Waterford Institute of Technology, Java interface Lecture 15 15/34

Polymorphism Polymorphism: derived from Greek: poly : many morph : able to change form Provision of single interface to objects of different types Waterford Institute of Technology, Java interface Lecture 15 16/34

Polymorphism Here element a reference to Drawable variable No way to know what class type referenced Only that class implements Drawable Therefore object has method draw(). Array<Drawable> elements;//elements contains Houses, Trees, Triangles,... Drawable element = elements.get(i);//specific member of elements index i Waterford Institute of Technology, Java interface Lecture 15 17/34

An example of polymorphism draw() method can draw different shapes depending on how implemented in each class As for-each loop traverses elements in list element.draw(); may call different methods House draw method Triangle draw method Tree draw method Class whose draw() method invoked must implement Drawable ArrayList<Drawable> elements;//elements contains Houses, Trees, Triangles,... for (Drawable element : elements) element.draw(); Waterford Institute of Technology, Java interface Lecture 15 18/34

Polymorphism in action Facilitates system expansion public class Circle implements Drawable... public void draw()... ArrayList<Drawable> elements = new ArrayList<>(); elements.add(new House(100, 200)); elements.add(new House(150, 250)); elements.add(new Tree(100, 200, 400)); elements.add(new Tree(500, 150, 250)); / add the circle object to existing list Drawable types / elements.add(new Circle(200, 400, 150); for(drawable element : elements) element.draw(); Waterford Institute of Technology, Java interface Lecture 15 19/34

Class implementing multiple interfaces Class may implement any number interfaces Each class must implement all interface methods public interface Moveable void moveto(int x, int y); public interface Drawable void draw(); public class Circle implements Moveable, Drawable public void moveto(int x, int y)... public void draw()... Waterford Institute of Technology, Java interface Lecture 15 20/34

What you may and may not do public class Circle() implements Moveable, Drawable public void moveto(...)... public void draw()... public scale(int x, int y)... Drawable drawable = new Circle(); drawable.draw(); // ok: draw in Drawable drawable.scale(); // error: scale not in Drawable drawable.moveto(); // error: moveto not in Drawable Moveable moveable = new Circle(); moveable.draw(); // error: draw not in Moveable moveable.moveto(); // ok: moveto in Moveable Waterford Institute of Technology, Java interface Lecture 15 21/34

Class implementing multiple interfaces instanceof test Drawable list references House, Tree and Circle objects These 3 classes implement Drawable Only Circle and Tree implement Moveable How to use existing ArrayList Drawable? for(drawable element : elements) if(element instanceof Moveable) Moveable m = (Moveable)element;//Cast element to Moveable m.moveto(10, 10); Cast Drawable to Moveable Waterford Institute of Technology, Java interface Lecture 15 22/34

Class implementing multiple interfaces Casting Moveable m = (Moveable)element; Casts the object to Moveable type moveto cannot be invoked on element element is Drawable so does not have moveto method for(drawable element : elements) if(element instanceof Moveable) ((Moveable)element).moveTo(10, 10); Waterford Institute of Technology, Java interface Lecture 15 23/34

Casting Verbose and compact Verbose if(element instanceof Moveable) Moveable m = (Moveable)element; m.moveto(10, 10); Compact if(element instanceof Moveable) ((Moveable)element).moveTo(10, 10); Waterford Institute of Technology, Java interface Lecture 15 24/34

Algorithm reuse Algorithm: obtain maximum size rectangle in array Rectangle objects public static double maximum(rectangle[] rects) //Error check should be included to ensure array has values double max = rects[0].getarea(); for(int i = 1; i < rects.length; i += 1) if(rects[i].getarea() > max) max = rects[i].getarea(); return max; Waterford Institute of Technology, Java interface Lecture 15 25/34

Algorithm reuse Algorithm: obtain maximum volume sphere in array Sphere objects public static double maximum(sphere[] spheres) //Error check should be included to ensure array has values double max = spheres[0].getarea(); for(int i = 1; i < spheres.length; i += 1) if(spheres[i].getarea() > max) max = spheres[i].getarea(); return max; Waterford Institute of Technology, Java interface Lecture 15 26/34

Algorithm reuse å We may require such algorithms for several types Here s how to use interfaces to unify behaviour: Create a Measurable interface Refactor Rectangle and Sphere as follows Have classes implement Measurable interface Implement the getmeasure() methods in each class Develop Data class to Traverse array Measureable objects Discover object generating maximum value Develop a TestData class to test the system //Create Measurable interface public interface Measurable double getmeasure(); Waterford Institute of Technology, Java interface Lecture 15 27/34

Algorithm reuse Refactored Rectangle class implements Measurable class Rectangle implements Measurable private double length; private double width; public Rectangle(double length, double width) this.length = length; this.width = width; / @return returns area rectangle / @Override public double getmeasure() return length width; Waterford Institute of Technology, Java interface Lecture 15 28/34

Algorithm reuse Refactored Sphere class implements Measurable class Sphere implements Measurable private double radius; public Sphere(double radius) this.radius = radius; / @return returns volume sphere / @Override public double getmeasure() return 4 Math.PI radius radius radius/3; Waterford Institute of Technology, Java interface Lecture 15 29/34

Algorithm reuse Data class to calculate maximum measured quantity public class Data public static Measurable maximum(measurable[] objects) if (objects.length == 0) return null; Measurable max = objects[0]; for (int i = 1; i < objects.length; i += 1) if(objects[i].getmeasure() > max.getmeasure()) max = objects[i]; return max; Waterford Institute of Technology, Java interface Lecture 15 30/34

Algorithm reuse TestData class to demo system public class TestData public void testdata() Sphere[] spheres = new Sphere(100), new Sphere(200), new Sphere(250), new Sphere(300) ; Measurable largest = Data.maximum(spheres); System.out.println("Largest: "+largest); Waterford Institute of Technology, Java interface Lecture 15 31/34

Polymorphism in action tostring implementations Rectangle and Sphere @Override public String tostring() return "Sphere [radius=" + radius + " volume= "+getmeasure()+"]"; @Override public String tostring() return "Rectangle [length =" + length + "width =" + width +" area= "+getmeasure()+"]"; Waterford Institute of Technology, Java interface Lecture 15 32/34

Summary Java interface an abstract class type Instantiation disallowed Instance of class (object) assignable to interface variable Facilitates unifying common behaviour Facilitates algorithm reuse Waterford Institute of Technology, Java interface Lecture 15 33/34

Referenced Material 1. Working with Interfaces and Inner Classes in Java (Cornell & Horstmann) www.informit.com/articles/article.aspx?p=1998555 [Accessed 2016-04-05] Waterford Institute of Technology, Java interface Lecture 15 34/34