Java Programming. Abstract classes and Interfaces

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

Generics method and class definitions which involve type parameters.

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

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

Chapter 6: Inheritance

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

CSE 143 Lecture 20. Circle

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

1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4'

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

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

Introduction to Java. CSC212 Lecture 6 D. Thiebaut, Fall 2014

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

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

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

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

Today. Reading. Homework. Lecture Notes CPSC 224 (Spring 2012) hashcode() method. Collections class. Ch 9: hw 7 out (due in a week)

COMP 250. inheritance (cont.) interfaces abstract classes

generic programming alberto ferrari university of parma

Primitive Java Generic Class

Lesson11-Inheritance-Abstract-Classes. The GeometricObject case

ITI Introduction to Computing II

C18a: Abstract Class and Method

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions

EXAMINATIONS 2013 Trimester 1 SWEN221. Software Development. Closed Book. There are 180 possible marks on the exam.

Implementing non-static features

CS/ENGRD 2110 SPRING 2018

Advanced Placement Computer Science. Inheritance and Polymorphism

Java Comparable interface

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

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

We are on the GUI fast track path

Abstract Class (2) Abstract Classes and Interfaces. Abstract Class (1) Abstract Class (3) EECS2030: Advanced Object Oriented Programming Fall 2017

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Abstract Classes and Interfaces

Binghamton University. CS-140 Fall Functional Java

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

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Java Generics

Collections Algorithms

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

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

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Polymorphism CSCI 201 Principles of Software Development

Practice Midterm 1. Problem Points Score TOTAL 50

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Inheritance, and Polymorphism.

Generics, I/O & Regular Expressions Maria Zontak

CS 310: HW 1, Junit, Generics Review

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting

CMP-326 Exam 2 Spring 2018 Total 120 Points Version 1

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name:

ITI Introduction to Computing II

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

CSCE145 Test 2-Review 03/29/2015 Hongkai Yu

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

ITI Introduction to Computing II

Chapter 11 Classes Continued

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

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

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

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions.

CMSC 202. Generics II

Lecture Notes Chapter #9_c Abstract Classes & Interfaces

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

EECS2030 Week 7 worksheet Tue Feb 28, 2017

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

1.00/ Introduction to Computers and Engineering Problem Solving. Quiz 2 / November 5, 2004

CSC 1214: Object-Oriented Programming

ITI Introduction to Computing II

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism

AP CS Unit 6: Inheritance Programs

Introduction to Computer Science Unit 4B. Programs: Classes and Objects

Chapter 14 Abstract Classes and Interfaces

ITI Introduction to Computing II

CS1150 Principles of Computer Science Objects and Classes

Generalized Code. Fall 2011 (Honors) 2

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

Java Generics -- an introduction. Based on

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

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

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList:

Closed book but one sheet, both sides, of A4 paper is allowed. Section 2.5 of the text Generics in the Java Programming Languages by Gilad Bracha

The Nervous Shapes Example

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

Inheritance, Polymorphism, and Interfaces

Exceptions & Miscellaneous Lecture 17

Binghamton University. CS-140 Fall Functional Java

Outline. applications of hashing equality and comparisons in Java sorting selection sort bubble sort insertion sort

Java Primer. CITS2200 Data Structures and Algorithms. Topic 0

Inheritance (an intuitive description)

Object-Oriented Design Lecture 11 CS 3500 Spring 2010 (Pucella) Tuesday, Feb 16, 2010

Session 04 - Object-Oriented Programming 1 Self-Assessment

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

Exercises C-Programming

Inheritance and Interfaces

CISC 1600 Lecture 3.1 Introduction to Processing

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Java interface Lecture 15

Transcription:

Java Programming Abstract classes and Interfaces

Classes A class is composed of data methods public class Rectangle { private double width, height; public Rectangle(double width, double height) { this.width= width; this.height=height; public double getarea() { return width * height; public double getperimeter() { return 2 * (width + height); A class defines a data type. public double getaspectratio() { return width / height;

Clients The class (or type) of an object defines the data that is managed by the object the methods we can apply on the object public void processrectangle(rectangle r) { double x1 = r.getarea(); double x2 = r.getperimeter(); double x3 = r.getaspectratio(); String x4 = r.tostring(); boolean x5 = r.equals( Rectangle ); public class Rectangle { private double width, height; public Rectangle(double width, double height) { this.width= width; this.height=height; public double getarea() { return width * height; public double getperimeter() { return 2 * (width + height); public double getaspectratio() { return width / height;

Interface An interface is a collection of method signatures access control return type method name formal parameters exceptions An interface must be implemented to define the method bodies define the data

Interface example public interface Shape { public double getarea(); public double getperimeter(); public double getaspectratio(); collection of method signatures the methods are fully defined public class Rectangle implements Shape { private double width, height; public Rectangle(double width, double height) { this.width= width; this.height=height; public double getarea() { return width * height; public double getperimeter() { return 2 * (width + height); public double getaspectratio() { return width / height;

Interfaces An interface cannot be instantiated Shape s = new Shape(); Shape s = new Rectangle(30, 10); An implementation must either define all methods OR be labeled as abstract Implementation denotes an is-a relationship public class Rectangle implements Shape means that a Rectangle is-a Shape

Implement three Shapes Rectangle A box with width & height height Isosceles Triangle A triangle with two equal sides width height Ellipse an oval with major/minor axis width width height

Implementation public interface Shape { public double getarea(); public double getperimeter(); public double getaspectratio(); // Constructing and naming a rectangle Shape x = new Rectangle(10,30); public class Rectangle implements Shape { private double width, height; public Rectangle(double width, double height) { this.width= width; this.height=height; public double getarea() { return width * height; width height public double getperimeter() { return 2 * (width + height); public double getaspectratio() { return width / height;

Implementation public interface Shape { public double getarea(); public double getperimeter(); public double getaspectratio(); // Constructing and naming a triangle Shape x = new IsocelesTriangle(10,30); public class IsocelesTriangle implements Shape { private double width, height; public IsocelesTriangle (double width, double height) { this.width= width; this.height=height; public double getarea() { return width * height / 2; width height public double getperimeter() { return 2*Math.sqrt(width*width/4 + height*height) + width; public double getaspectratio() { return width / height;

Implementation public interface Shape { public double getarea(); public double getperimeter(); public double getaspectratio(); // Constructing and naming an ellipse Shape x = new Ellipse(10,30); public class Ellipse implements Shape { private double width, height; public Ellipse(double width, double height) { this.width= width; this.height=height; public double getarea() { return Math.PI * width * height / 4; width height public double getperimeter() { double a= width/2, b = height/2; double x = Math.max(a,b), y = Math.min(a,b); int digits = 53; double tolerance = Math.sqrt(Math.pow(a, digits)); double s = 0, m = 1; while(x-y>tolerance*y) { double y1 = Math.sqrt(x*y); double x1 = (x+y)/2; x = x1; y = y1; m *= 2; s += m * Math.pow(x-y,2); return Math.PI * (Math.pow(a+b, 2)-s)/(x+y); public double getaspectratio() { return width / height;

Abstract Class public class Rectangle implements Shape { private double width, height; public Rectangle(double width, double height) { this.width= width; this.height=height; public double getarea() { return width * height; public class IsocelesTriangle implements Shape { private double width, height; public IsocelesTriangle (double width, double height) { this.width= width; this.height=height; public double getarea() { return width * height / 2; public class Ellipse implements Shape { private double width, height; public Ellipse(double width, double height) { this.width= width; this.height=height; public double getarea() { return Math.PI * width * height / 4; public double getperimeter() { return 2 * (width + height); public double getaspectratio() { return width / height; public double getperimeter() { return 2*Math.sqrt(width*width/4+height*height)+width; public double getaspectratio() { return width / height; Notice the similar code in these three implementations. Should aggregate into an abstract class. public double getperimeter() { double a= width/2, b = height/2; double x = Math.max(a,b), y = Math.min(a,b); int digits = 53; double tolerance = Math.sqrt(Math.pow(a, digits)); double s = 0, m = 1; while(x-y>tolerance*y) { double y1 = Math.sqrt(x*y); double x1 = (x+y)/2; x = x1; y = y1; m *= 2; s += m * Math.pow(x-y,2); return Math.PI * (Math.pow(a+b, 2)-s)/(x+y); public double getaspectratio() { return width / height;

Abstract Class public abstract class AbstractShape implements Shape { protected double width, height; public AbstractShape(double width, double height) { this.width= width; this.height=height; public double getaspectratio() { return width / height; public class Rectangle extends AbstractShape { public Rectangle(double width, double height) { super(width, height); public double getarea() { return width * height; public double getperimeter() { return 2 * (width + height); public class IsocelesTriangle extends AbstractShape { public IsocelesTriangle (double width, double height) { super(width,height); public double getarea() { return width * height / 2; public double getperimeter() { return 2*Math.sqrt(width*width/4+height*height)+width; public class Ellipse extends AbstractShape { public Ellipse(double width, double height) { super(width, height); public double getarea() { return Math.PI * width * height / 4; public double getperimeter() { double a= width/2, b = height/2; double x = Math.max(a,b), y = Math.min(a,b); int digits = 53; double tolerance = Math.sqrt(Math.pow(a, digits)); double s = 0, m = 1; while(x-y>tolerance*y) { double y1 = Math.sqrt(x*y); double x1 = (x+y)/2; x = x1; y = y1; m *= 2; s += m * Math.pow(x-y,2); return Math.PI * (Math.pow(a+b, 2)-s)/(x+y);

An abstract class is not completely defined may have methods may have data will usually have a collection of method signatures cannot be instantiated AbstractShape s = new AbstractShape(3, 5); AbstractShape s = new Rectangle(3, 5); Abstract Class

public interface Shape { public double getarea(); public double getperimeter(); public double getaspectratio(); public class ShapeMaker { public static Shape getrandomshape() { double width = Math.random() * 20; double height = Math.random() * 20; int type = (int) (Math.random() * 3); switch (type) { case 0: return new Ellipse(width, height); case 1: return new IsocelesTriangle(width, height); case 2: return new Rectangle(width, height); throw new IllegalArgumentException(); public static double totalarea(list<shape> shapes) { double totalarea = 0; for(shape s : shapes) { totalarea += s.getarea(); return totalarea; public static void main(string[] args) { List<Shape> shapes = new LinkedList<Shape>(); for (int i = 0; i < 20; i++) { shapes.add(getrandomshape()); System.out.println(totalArea(shapes));

Generics A generic class is a class that is parameterized over types. T1 and T2 are type parameters. Type arguments are supplied when the class is used. public class Pair<T1,T2> { private T1 first; private T2 second; public Pair(T1 first, T2 second) { this.first = first; this.second = second; public class PairDriver { public static void main(string[] args) { Pair<String, Integer> p1 = new Pair<>( Kenny, 1); Pair<Integer, Double> p2 = new Pair<>(2, 3.5); String x1 = p1.getfirst(); Integer x2 = p1.getsecond(); Integer x3 = p2.getfirst(); Double x4 = p2.getsecond(); Pair<Pair<String, Integer>,Pair<Integer, Double>> p3 = new Pair<>(p1, p2);??? x5 = p3.getfirst();??? x6 = p3.getsecond(); public T1 getfirst() { return first; public T2 getsecond() { return second; public void setfirst(t1 first) { this.first = first; public void setsecond(t2 second) { this.second = second;

Java has two commonly used interfaces Comparable<T> Comparable & Comparator public interface Comparable<T> { public int compareto(t e); This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering. The compareto method this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object. public interface Comparator<T> { public int compare(t e1, T e2); Comparator<T> A comparison function, which imposes a total ordering on some collection of objects. The compare method compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Example Can the AbstractShape class implement the Comparable interface? We define the natural ordering of shapes by keying on the area. public abstract class AbstractShape implements Shape, Comparable<Shape> { protected double width, height; public AbstractShape(double width, double height) { this.width = width; this.height = height; public double getaspectratio() { return width / height; public int compareto(shape e) { double diff = getarea() e.getarea(); if(diff < 0) { return -1; else if(diff > 0) { return 1; else { return 0;

Why the interface? public static AbstractShape getsmallest(abstractshape[] shapes) { if(shapes.length == 0) throw new NoSuchElementException(); AbstractShape smallest = shapes[0]; for(int i=1; i<shapes.length; i++){ if(shapes[i].compareto(smallest) < 0) { smallest = shapes[i]; return smallest; Could write code like this. It finds the smallest shape in an array of AbstractShapes. public static void example() { AbstractShape[] shapes = new AbstractShape[10]; for(int i=0; i<10; i++) { shapes[i] = getrandomshape(); AbstractShape smallest = getsmallest(shapes);

Why the interface? public static Comparable getsmallest(comparable[] items) { if(items.length == 0) throw new NoSuchElementException(); Comparable smallest = items[0]; for(int i=1; i<items.length; i++){ if(items[i].compareto(smallest) < 0) { smallest = items[i]; return smallest; Better to write code like this. It finds the smallest thing in an array of things. public static void example() { AbstractShape[] shapes = new AbstractShape[10]; for(int i=0; i<10; i++) { shapes[i] = getrandomshape(); AbstractShape smallest = getsmallest(shapes);

Generic Methods Methods can introduce type parameters Generic type parameter public <T> T randomchoice(t x1, T x2) { if(math.random() <.5) { return x1; else { return x2; String s = randomchoice( a, b ); Double x = randomchoice(1.0, 2.3); Integer y = randomchoice(3,5); Shape u = new Rectangle(10,30); Shape v = new Rectangle(30, 50); Shape t = randomchoice(u, v);

Generic Methods Can we write a generic method to accept to elements of some type and return the smallest element? public <T> T smallest(t x1, T x2) { if(x1 < x2) { return x1; else { return x2; This doesn t work since the < operator is not supported on object types. public <T> T smallest(t x1, T x2) { if(x1.compareto(x2) < 0) { return x1; else { return x2; This doesn t work since the compareto method is not supported on objects that don t implement Comparable.

Generic Methods Can we write a generic method to accept elements of some type and return the smallest element? public <T extends Comparable<T>> T smallest(t x1, T x2) { if(x1.compareto(x2) < 0) { return x1; else { return x2; This works since T has an upper bound of Comparable<T>. This means that whatever T is, it is a subclass of Comparable<T>. String x1 = smallest( a, b ); Integer x2 = smallest(15, 3); Double x3 = smallest(2, -18); Notation to put an upper-bound on a methods generic parameter TYPENAME extends UPPERBOUND Examples: <T extends JPanel> <T extends Comparable<T>> <T extends JComponent>

Generics and Subtyping Consider the following example. What are the conformance rules for generic classes? Pair<Object, Object> p1 = new Pair<Object,Object>( a, b ); p1.setfirst(4); // IS THIS VALID? p1.setsecond( c ); // IS THIS VALID? Pair<String, Integer> p2 = new Pair<String, Integer>( a, 3); p2.setfirst(4); // IS THIS VALID? p2.setsecond( c ); // IS THIS VALID? p1 = p2; // IS THIS VALID? p1.setfirst(4); p1.setsecond( c );

Conformance rules Generics and Conformance If A is a non-generic super-class of B then objects of type B conform to A Shape s = new Rectangle(10,30); Number x = new Double(3.5); If A is a generic super-class of B, then objects of B type conform to A only if each generic parameter is an exact match. List<Shape> x = new LinkedList<Rectangle>; List<Shape> y = new LinkedList<Shape>;

Bounded Type Parameters When a method declares a parameterized type, the actual parameters must match exactly. public Object pickone(twoofakind<object> pair) { if(math.random() <. 5) { return pair.getfirst(); else { return pair.getsecond(); TwoOfAKind<String> p1 = new TwoOfAKind<String>( a, b ); TwoOfAKind<Object> p2 = new TwoOfAKind<Object>(1, c ); Object x = pickone(p1); Object y = pickone(p2); public class TwoOfAKind<T> { private T first; private T second; public TwoOfAKind (T first, T second) { this.first = first; this.second = second; public T getfirst() { return first; public T getsecond() { return second; public void setfirst(t first) { this.first = first; public void setsecond(t second) { this.second = second;

Generics and Wildcards Wildcards allow us to write truly generic functions.? denotes ANY TYPE public Object pickone(twoofakind<?> pair) { if(math.random() <. 5) { return pair.getfirst(); else { return pair.getsecond(); TwoOfAKind<String> p1 = new TwoOfAKind<String>( a, b ); TwoOfAKind<Object> p2 = new TwoOfAKind<Object>(1, c ); Object x = pickone(p1); Object y = pickone(p2);

Generics and Wildcards The wildcard can be constrained. If A is the name of some class then? extends A the? stands for some class that is either class A or a SUB CLASS OF A A is an upper-bound public Comparable pickone(twoofakind<? extends Comparable> pair) { if(math.random() <. 5) { return pair.getfirst(); else { return pair.getsecond(); TwoOfAKind<String> p1 = new TwoOfAKind<String>( a, b ); TwoOfAKind<Object> p2 = new TwoOfAKind<Object>(1, c ); Object x = pickone(p1); Object y = pickone(p2);

Generics and Wildcards The wildcard can be constrained. If A is the name of some class then? super A the? stands for some class that is either class A OR A SUPER CLASS OF A A is a lower-bound public Object pickone(twoofakind<? super Integer> pair) { if(math.random() <. 5) { return pair.getfirst(); else { return pair.getsecond(); TwoOfAKind<String> p1 = new TwoOfAKind<String>( a, b ); TwoOfAKind<Number> p2 = new TwoOfAKind<Number>(1, 3.5); Object x = pickone(p1); Object y = pickone(p2);

Generic Interface Example public interface Function<X,Y> { public Y apply(x x); The interface describes one function public class Square implements Function<Double, Double> { public Double apply(double x) { return x * x; public class iseven implements Function<Integer, Boolean> { public Boolean apply(integer x) { return x % 2 == 0; Each of these non-abstract classes defines that function. public class Redness implements Function<Color, Integer> { public Integer apply(color color) { return color.getred();