Java Programming. Abstract classes and Interfaces

Size: px
Start display at page:

Download "Java Programming. Abstract classes and Interfaces"

Transcription

1 Java Programming Abstract classes and Interfaces

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

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

4 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

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

6 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

7 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

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

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

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

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

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

13 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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

COMP 250. Lecture 29. interfaces. Nov. 18, 2016 COMP 250 Lecture 29 interfaces Nov. 18, 2016 1 ADT (abstract data type) ADT s specify a set of operations, and allow us to ignore implementation details. Examples: list stack queue binary search tree priority

More information

Generics method and class definitions which involve type parameters.

Generics method and class definitions which involve type parameters. Contents Topic 07 - Generic Programming I. Introduction Example 1 User defined Generic Method: printtwice(t x) Example 2 User defined Generic Class: Pair Example 3 using java.util.arraylist II. Type

More information

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

JAVA PROGRAMMING LAB. ABSTRACT In this Lab you will learn how to describe objects and classes and how to define classes and create objects Islamic University of Gaza Faculty of Engineering Computer Engineering Dept Computer Programming Lab (ECOM 2114) ABSTRACT In this Lab you will learn how to describe objects and classes and how to define

More information

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

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 FALL 2017 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due tomorrow night (17 February) Get started on A3 a method every other day.

More information

Chapter 6: Inheritance

Chapter 6: Inheritance Chapter 6: Inheritance EECS 1030 moodle.yorku.ca State of an object final int WIDTH = 3; final int HEIGTH = 4; final int WEIGHT = 80; GoldenRectangle rectangle = new GoldenRectangle(WIDTH, HEIGHT, WEIGHT);

More information

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

CS/ENGRD 2110 FALL Lecture 7: Interfaces and Abstract Classes 1 CS/ENGRD 2110 FALL 2016 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 Announcements 2 Attendance for this week s recitation is mandatory! A2 is due Today Get started

More information

CSE 143 Lecture 20. Circle

CSE 143 Lecture 20. Circle CSE 143 Lecture 20 Abstract classes Circle public class Circle { private double radius; public Circle(double radius) { this.radius = radius; public double area() { return Math.PI * radius * radius; public

More information

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

Chapter 21- Using Generics Case Study: Geometric Bunch. Class: Driver. package csu.matos; import java.util.arraylist; public class Driver { Chapter 21- Using Generics Case Study: Geometric Bunch In this example a class called GeometricBunch is made to wrap around a list of GeometricObjects. Circle and Rectangle are subclasses of GeometricObject.

More information

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

1. Which of the following is the correct expression of character 4? a. 4 b. 4 c. '\0004' d. '4' Practice questions: 1. Which of the following is the correct expression of character 4? a. 4 b. "4" c. '\0004' d. '4' 2. Will System.out.println((char)4) display 4? a. Yes b. No 3. The expression "Java

More information

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

More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario More About Classes CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario The Story So Far... Classes as collections of fields and methods. Methods can access fields, and

More information

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

Abstract Class. Lecture 21. Based on Slides of Dr. Norazah Yusof Abstract Class Lecture 21 Based on Slides of Dr. Norazah Yusof 1 Abstract Class Abstract class is a class with one or more abstract methods. The abstract method Method signature without implementation

More information

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

Introduction to Java. CSC212 Lecture 6 D. Thiebaut, Fall 2014 Introduction to Java CSC212 Lecture 6 D. Thiebaut, Fall 2014 What is it? It is always surprising It is common in most programming languages It is a natural way to save computer resources Most compilers

More information

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber Chapter 10 Inheritance and Polymorphism Dr. Hikmat Jaber 1 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common features. What is the

More information

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

COMP200 ABSTRACT CLASSES. OOP using Java, from slides by Shayan Javed 1 1 COMP200 ABSTRACT CLASSES OOP using Java, from slides by Shayan Javed Abstract Classes 2 3 From the previous lecture: public class GeometricObject { protected String Color; protected String name; protected

More information

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

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community CSCI-12 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community http://csc.cs.rit.edu 1. Provide a detailed explanation of what the following code does: 1 public boolean checkstring

More information

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

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name: CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, 2017 Name: 1. (10 points) For the following, Check T if the statement is true, the F if the statement is false. (a) T F : If a child overrides

More information

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

Today. Reading. Homework. Lecture Notes CPSC 224 (Spring 2012) hashcode() method. Collections class. Ch 9: hw 7 out (due in a week) Today hashcode() method Collections class Reading Ch 9: 406-424 Homework hw 7 out (due in a week) S. Bowers 1 of 9 The Object hashcode() function The signature: public int hashcode() What it does: returns

More information

COMP 250. inheritance (cont.) interfaces abstract classes

COMP 250. inheritance (cont.) interfaces abstract classes COMP 250 Lecture 31 inheritance (cont.) interfaces abstract classes Nov. 20, 2017 1 https//goo.gl/forms/ymqdaeilt7vxpnzs2 2 class Object boolean equals( Object ) int hashcode( ) String tostring( ) Object

More information

generic programming alberto ferrari university of parma

generic programming alberto ferrari university of parma generic programming alberto ferrari university of parma contents generic programming java generic programming methods & generic programming classes & generic programming java with generics generic methods

More information

Primitive Java Generic Class

Primitive Java Generic Class Primitive Java Generic Class 1 A buffer pool is a data structure that caches records retrieved from a disk file, in order to improve an application's performance. Typically, the pool stores some sort of

More information

Lesson11-Inheritance-Abstract-Classes. The GeometricObject case

Lesson11-Inheritance-Abstract-Classes. The GeometricObject case Lesson11-Inheritance-Abstract-Classes The GeometricObject case GeometricObject class public abstract class GeometricObject private string color = "White"; private DateTime datecreated = new DateTime(2017,

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Interface Abstract data types Version of January 26, 2013 Abstract These lecture notes are meant

More information

C18a: Abstract Class and Method

C18a: Abstract Class and Method CISC 3115 TY3 C18a: Abstract Class and Method Hui Chen Department of Computer & Information Science CUNY Brooklyn College 10/31/2018 CUNY Brooklyn College 1 Outline Recap Inheritance and polymorphism Abstract

More information

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

CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions Name CISC 3115 Modern Programming Techniques Spring 2018 Section TY3 Exam 2 Solutions 1. a. (25 points) A rational number is a number that can be represented by a pair of integers a numerator and a denominator.

More information

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

EXAMINATIONS 2013 Trimester 1 SWEN221. Software Development. Closed Book. There are 180 possible marks on the exam. T E W H A R E W Ā N A N G A O T E Ū P O K O O T E I K A A M Ā U I VUW V I C T O R I A UNIVERSITY OF WELLINGTON Student ID:..................... EXAMINATIONS 2013 Trimester 1 SWEN221 Software Development

More information

Implementing non-static features

Implementing non-static features Implementing non-static features Problem Implement the Rectangle class. What have we done so far? attributes constructors accessors mutators getarea tostring scale equals compareto Duplicates What will

More information

CS/ENGRD 2110 SPRING 2018

CS/ENGRD 2110 SPRING 2018 CS/ENGRD 2110 SPRING 2018 Lecture 7: Interfaces and http://courses.cs.cornell.edu/cs2110 1 2 St Valentine s Day! It's Valentines Day, and so fine! Good wishes to you I consign.* But since you're my students,

More information

Advanced Placement Computer Science. Inheritance and Polymorphism

Advanced Placement Computer Science. Inheritance and Polymorphism Advanced Placement Computer Science Inheritance and Polymorphism What s past is prologue. Don t write it twice write it once and reuse it. Mike Scott The University of Texas at Austin Inheritance, Polymorphism,

More information

Java Comparable interface

Java Comparable interface Java Comparable interface Recall that to define a binary search tree, the elements that we are considering must be comparable to each other, meaning that there must be a well-defined ordering. For strings

More information

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

AShape.java Sun Jan 21 22:32: /** * Abstract strategy to compute the area of a geometrical shape. Dung X. Nguyen * * Copyright AShape.java Sun Jan 21 22:32:31 2001 1 Abstract strategy to compute the area of a geometrical shape. @author Dung X. Nguyen Copyright 1999 by Dung X. Nguyen - All rights reserved. Modifications by Alan

More information

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

First Name: AITI 2004: Exam 2 July 19, 2004 First Name: AITI 2004: Exam 2 July 19, 2004 Last Name: JSP Track Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot understand

More information

We are on the GUI fast track path

We are on the GUI fast track path We are on the GUI fast track path Chapter 13: Exception Handling Skip for now Chapter 14: Abstract Classes and Interfaces Sections 1 9: ActionListener interface Chapter 15: Graphics Skip for now Chapter

More information

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

Abstract Class (2) Abstract Classes and Interfaces. Abstract Class (1) Abstract Class (3) EECS2030: Advanced Object Oriented Programming Fall 2017 Abstract Class (2) Abstract Classes and Interfaces EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG public abstract class Polygon { double[] sides; Polygon(double[] sides) { this.sides

More information

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

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science mluckner@mini.pw.edu.pl http://www.mini.pw.edu.pl/~lucknerm } Generics allow the programer to create an universal

More information

Abstract Classes and Interfaces

Abstract Classes and Interfaces Abstract Classes and Interfaces EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG Abstract Class (1) Problem: A polygon may be either a triangle or a rectangle. Given a polygon, we

More information

Binghamton University. CS-140 Fall Functional Java

Binghamton University. CS-140 Fall Functional Java Functional Java 1 First Class Data We have learned how to manipulate data with programs We can pass data to methods via arguments We can return data from methods via return types We can encapsulate data

More information

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

COMP200 INHERITANCE. OOP using Java, from slides by Shayan Javed 1 1 COMP200 INHERITANCE OOP using Java, from slides by Shayan Javed 2 Inheritance Derive new classes (subclass) from existing ones (superclass). Only the Object class (java.lang) has no superclass Every

More information

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

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Java Generics 1 CSCE 314: Programming Languages Dr. Flemming Andersen Java Generics 2 Detour: Rules for Method Overriding (1) CSCE 314 TAMU Fall 2017 1. The argument list should be exactly the same as that of the overridden

More information

Collections Algorithms

Collections Algorithms Collections Algorithms 1 / 11 The Collections Framework A collection is an object that represents a group of objects. The collections framework allows different kinds of collections to be dealt with in

More information

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

First Name: AITI 2004: Exam 2 July 19, 2004 First Name: AITI 2004: Exam 2 July 19, 2004 Last Name: Standard Track Read Instructions Carefully! This is a 3 hour closed book exam. No calculators are allowed. Please write clearly if we cannot understand

More information

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

COMP 250. Lecture 32. interfaces. (Comparable, Iterable & Iterator) Nov. 22/23, 2017 COMP 250 Lecture 32 interfaces (Comparable, Iterable & Iterator) Nov. 22/23, 2017 1 Java Comparable interface Suppose you want to define an ordering on objects of some class. Sorted lists, binary search

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2 CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,

More information

Polymorphism CSCI 201 Principles of Software Development

Polymorphism CSCI 201 Principles of Software Development Polymorphism CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Program Outline USC CSCI 201L Polymorphism Based on the inheritance hierarchy, an object with a compile-time

More information

Practice Midterm 1. Problem Points Score TOTAL 50

Practice Midterm 1. Problem Points Score TOTAL 50 CS 120 Software Design I Spring 2019 Practice Midterm 1 University of Wisconsin - La Crosse February 25 NAME: Do not turn the page until instructed to do so. This booklet contains 10 pages including the

More information

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Abstract Classes Interfaces CSCI 201 Principles of Software Development Abstract Classes Interfaces CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Abstract Classes Outline USC CSCI 201L Abstract Classes An abstract class is a way for

More information

Abstract Classes Interfaces CSCI 201 Principles of Software Development

Abstract Classes Interfaces CSCI 201 Principles of Software Development Abstract Classes Interfaces CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Abstract Classes Outline USC CSCI 201L Abstract Classes An abstract class is a way for

More information

Inheritance, and Polymorphism.

Inheritance, and Polymorphism. Inheritance and Polymorphism by Yukong Zhang Object-oriented programming languages are the most widely used modern programming languages. They model programming based on objects which are very close to

More information

Generics, I/O & Regular Expressions Maria Zontak

Generics, I/O & Regular Expressions Maria Zontak Generics, I/O & Regular Expressions Maria Zontak Credits: CS143 course I taught in North Seattle College CS5004 course built by Dr. Therapon Skotiniotis here in Northeastern Slides on Regular Expressions

More information

CS 310: HW 1, Junit, Generics Review

CS 310: HW 1, Junit, Generics Review CS 310: HW 1, Junit, Generics Review Chris Kauffman Week 2-1 Logistics At Home Read Weiss Ch 5: Big-O Read Weiss Ch 15: ArrayList implementation HW 1: Posted, due end of next week Reminder to DrJava Users

More information

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

Overview. ITI Introduction to Computing II. Interface 1. Problem 1. Problem 1: Array sorting. Problem 1: Array sorting. Problem 1: Array sorting Overview ITI 1121. Introduction to Computing II Rafael Falcon and Marcel Turcotte (with contributions from R. Holte) Electrical Engineering and Computer Science University of Ottawa Interface Abstract

More information

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

CMP-326 Exam 2 Spring 2018 Total 120 Points Version 1 Version 1 5. (10 Points) What is the output of the following code: int total = 0; int i = 0; while( total < 90 ) { switch( i ) { case 0: total += 30; i = 1; break; case 1: i = 2; total -= 15; case 2: i

More information

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

CS-140 Fall 2018 Test 2 Version A Nov. 12, Name: CS-140 Fall 2018 Test 2 Version A Nov. 12, 2018 Name: 1. (10 points) For the following, Check T if the statement is true, or F if the statement is false. (a) X T F : A class in Java contains fields, and

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

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

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java

More information

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

CSCE145 Test 2-Review 03/29/2015 Hongkai Yu CSCE145 Test 2-Review 03/29/2015 Hongkai Yu 1. What results are printed when the main method in TestBase is executed? public class Base private int value; public Base(int x) value = x; System.out.println(

More information

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

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Software Paradigms (Lesson 3) Object-Oriented Paradigm (2) Table of Contents 1 Reusing Classes... 2 1.1 Composition... 2 1.2 Inheritance... 4 1.2.1 Extending Classes... 5 1.2.2 Method Overriding... 7 1.2.3

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

Chapter 11 Classes Continued

Chapter 11 Classes Continued Chapter 11 Classes Continued The real power of object-oriented programming comes from its capacity to reduce code and to distribute responsibilities for such things as error handling in a software system.

More information

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

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017 Introduction to OOP with Java Instructor: AbuKhleif, Mohammad Noor Sep 2017 Lecture 11: Inheritance and Polymorphism Part 1 Instructor: AbuKhleif, Mohammad Noor Sep 2017 Instructor AbuKhleif, Mohammad

More information

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

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes CS/ENGRD 2110 SPRING 2019 Lecture 7: Interfaces and Abstract Classes http://courses.cs.cornell.edu/cs2110 1 Announcements 2 A2 is due Thursday night (14 February) Go back to Lecture 6 & discuss method

More information

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

About This Lecture. Data Abstraction - Interfaces and Implementations. Outline. Object Concepts. Object Class, Protocol and State. 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

More information

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

Parts of a Contract. Contract Example. Interface as a Contract. Wednesday, January 30, 13. Postcondition. Preconditions. Parts of a Contract Syntax - Method signature Method name Parameter list Return type Semantics - Comments Preconditions: requirements placed on the caller Postconditions: what the method modifies and/or

More information

CMSC 202. Generics II

CMSC 202. Generics II CMSC 202 Generics II Generic Sorting We can now implement sorting functions that can be used for any class (that implements Comparable). The familiar insertion sort is shown below.!! public static

More information

Lecture Notes Chapter #9_c Abstract Classes & Interfaces

Lecture Notes Chapter #9_c Abstract Classes & Interfaces Lecture Notes Chapter #9_c Abstract Classes & Interfaces Abstract Classes parent class child class more abstract more concrete, i.e., less abstract abstract class o class with an abstract modifier o class

More information

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

Inheritance and Polymorphism. CSE 114, Computer Science 1 Stony Brook University Inheritance and Polymorphism CSE 114, Computer Science 1 Stony Brook University http://www.cs.stonybrook.edu/~cse114 1 Motivation Model classes with similar properties and methods: Circles, rectangles

More information

EECS2030 Week 7 worksheet Tue Feb 28, 2017

EECS2030 Week 7 worksheet Tue Feb 28, 2017 1. Interfaces The Comparator interface provides a way to control how a sort method (such as Collections.sort) sorts elements of a collection. For example, the following main method sorts a list of strings

More information

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

S.O.L.I.D: Software Engineering Principles DCC / ICEx / UFMG S.O.L.I.D: Software Engineering Principles Eduardo Figueiredo http://www.dcc.ufmg.br/~figueiredo S.O.L.I.D Principles These principles intend to create systems that are easier to maintain

More information

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

1.00/ Introduction to Computers and Engineering Problem Solving. Quiz 2 / November 5, 2004 1.00/1.001 Introduction to Computers and Engineering Problem Solving Quiz 2 / November 5, 2004 Name: Email Address: TA: Section: You have 90 minutes to complete this exam. For coding questions, you do

More information

CSC 1214: Object-Oriented Programming

CSC 1214: Object-Oriented Programming CSC 1214: Object-Oriented Programming J. Kizito Makerere University e-mail: jkizito@cis.mak.ac.ug www: http://serval.ug/~jona materials: http://serval.ug/~jona/materials/csc1214 e-learning environment:

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes

More information

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

Polymorphism. CMSC 330: Organization of Programming Languages. Two Kinds of Polymorphism. Polymorphism Overview. Polymorphism CMSC 330: Organization of Programming Languages Polymorphism Polymorphism Definition Feature that allows values of different data types to be handled using a uniform interface Applicable to Functions Ø

More information

AP CS Unit 6: Inheritance Programs

AP CS Unit 6: Inheritance Programs AP CS Unit 6: Inheritance Programs Program 1. Complete the Rectangle class. The Rectangle public class Rectangle{ class represents private int x1, y1, x2, y2; a rectangle in a standard coordinate plane

More information

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

Introduction to Computer Science Unit 4B. Programs: Classes and Objects Introduction to Computer Science Unit 4B. Programs: Classes and Objects This section must be updated to work with repl.it 1. Copy the Box class and compile it. But you won t be able to run it because it

More information

Chapter 14 Abstract Classes and Interfaces

Chapter 14 Abstract Classes and Interfaces Chapter 14 Abstract Classes and Interfaces 1 What is abstract class? Abstract class is just like other class, but it marks with abstract keyword. In abstract class, methods that we want to be overridden

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance (part II) Polymorphism Version of January 21, 2013 Abstract These lecture notes

More information

CS1150 Principles of Computer Science Objects and Classes

CS1150 Principles of Computer Science Objects and Classes CS1150 Principles of Computer Science Objects and Classes Yanyan Zhuang Department of Computer Science http://www.cs.uccs.edu/~yzhuang CS1150 UC. Colorado Springs Object-Oriented Thinking Chapters 1-8

More information

Generalized Code. Fall 2011 (Honors) 2

Generalized Code. Fall 2011 (Honors) 2 CMSC 202H Generics Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using base classes is general, but restricted to a single class hierarchy

More information

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

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1 Java and OOP Part 3 Extending classes OOP in Java : W. Milner 2005 : Slide 1 Inheritance Suppose we want a version of an existing class, which is slightly different from it. We want to avoid starting again

More information

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html

Java Generics -- an introduction. Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Java Generics -- an introduction Based on https://docs.oracle.com/javase/tutorial/java/generics/why.html Generics vs. Templates Templates in C++ are compiled into unique code based on the types passed

More information

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

Chapter 11 Object-Oriented Design Exception and binary I/O can be covered after Chapter 9 Chapter 6 Arrays Chapter 7 Objects and Classes Chapter 8 Strings Chapter 9 Inheritance and Polymorphism GUI can be covered after 10.2, Abstract Classes Chapter 12 GUI Basics 10.2, Abstract Classes Chapter

More information

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

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

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

Interfaces. An interface defines a set of methods. An interface declaration contains signatures, but no implementations. Interface Interface definition Interface implementation by classes Benefits of interfaces Implementation of multiple interface Java Collection Framework Interfaces An interface defines a set of methods.

More information

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

Generic types. Announcements. Raw ArrayLists. Generic types (cont.) Creating a raw ArrayList: Accessing a raw ArrayList: Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide

More information

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

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 Announcements PS 3 is ready Midterm exam 1: Tuesday, April 11, in class Closed book but one sheet, both sides, of A4 paper is allowed Today s topic: Generics (parameterized types) Readings for this slide

More information

The Nervous Shapes Example

The Nervous Shapes Example The Nervous Shapes Example This Example is taken from Dr. King s Java book 1 11.6 Abstract Classes Some classes are purely artificial, created solely so that subclasses can take advantage of inheritance.

More information

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

Today. Book-keeping. Inheritance. Subscribe to sipb-iap-java-students. Slides and code at  Interfaces. Today Book-keeping Inheritance Subscribe to sipb-iap-java-students Interfaces Slides and code at http://sipb.mit.edu/iap/java/ The Object class Problem set 1 released 1 2 So far... Inheritance Basic objects,

More information

Inheritance, Polymorphism, and Interfaces

Inheritance, Polymorphism, and Interfaces Inheritance, Polymorphism, and Interfaces Chapter 8 Inheritance Basics (ch.8 idea) Inheritance allows programmer to define a general superclass with certain properties (methods, fields/member variables)

More information

Exceptions & Miscellaneous Lecture 17

Exceptions & Miscellaneous Lecture 17 Exceptions & Miscellaneous Lecture 17 Waterford Institute of Technology April 6, 2016 John Fitzgerald Waterford Institute of Technology, Exceptions & Miscellaneous Lecture 17 1/23 Presentation outline

More information

Binghamton University. CS-140 Fall Functional Java

Binghamton University. CS-140 Fall Functional Java Functional Java 1 First Class Data We have learned how to manipulate data with programs We can pass data to methods via arguments We can return data from methods via return types We can encapsulate data

More information

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

Outline. applications of hashing equality and comparisons in Java sorting selection sort bubble sort insertion sort Outline applications of hashing equality and comparisons in Java sorting selection sort bubble sort insertion sort 1 applications of hash tables hash tables can be used in any application where values

More information

Java Primer. CITS2200 Data Structures and Algorithms. Topic 0

Java Primer. CITS2200 Data Structures and Algorithms. Topic 0 CITS2200 Data Structures and Algorithms Topic 0 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies and Interfaces Exceptions Generics Reading: Lambert

More information

Inheritance (an intuitive description)

Inheritance (an intuitive description) Inheritance (an intuitive description) Recall the Orange class properties found in Orange are also shared with other Fruits (e.g. Apple, Banana, Pineapple) We associate behavior as well as state with with

More information

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

Object-Oriented Design Lecture 11 CS 3500 Spring 2010 (Pucella) Tuesday, Feb 16, 2010 Object-Oriented Design Lecture 11 CS 3500 Spring 2010 (Pucella) Tuesday, Feb 16, 2010 11 Polymorphism The functional iterator interface we have defined last lecture is nice, but it is not very general.

More information

Session 04 - Object-Oriented Programming 1 Self-Assessment

Session 04 - Object-Oriented Programming 1 Self-Assessment UC3M Alberto Cortés Martín Systems Programming, 2014-2015 version: 2015-02-06 Session 04 - Object-Oriented Programming 1 Self-Assessment Exercise 1 Rectangles Part 1.A Write a class called Rectangle1 that

More information

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

For this section, we will implement a class with only non-static features, that represents a rectangle For this section, we will implement a class with only non-static features, that represents a rectangle 2 As in the last lecture, the class declaration starts by specifying the class name public class Rectangle

More information

Exercises C-Programming

Exercises C-Programming Exercises C-Programming Claude Fuhrer (claude.fuhrer@bfh.ch) 0 November 016 Contents 1 Serie 1 1 Min function.................................. Triangle surface 1............................... 3 Triangle

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

CISC 1600 Lecture 3.1 Introduction to Processing

CISC 1600 Lecture 3.1 Introduction to Processing CISC 1600 Lecture 3.1 Introduction to Processing Topics: Example sketches Drawing functions in Processing Colors in Processing General Processing syntax Processing is for sketching Designed to allow artists

More information

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

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong: Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer

More information

Java interface Lecture 15

Java interface Lecture 15 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

More information