CSE 143 Lecture 20. Circle

Similar documents
CSE 143 Lecture 26. Advanced collection classes. (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, ,

Building Java Programs

CSE 143. Lecture 13: Interfaces, Comparable reading: , 16.4, 10.2

Building Java Programs. Interfaces and Comparable reading: , 10.2, 16.4

CSE 143 Lecture 14. Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4

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

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

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

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

Java Primer. CITS2200 Data Structures and Algorithms. Topic 2

COMP 250. inheritance (cont.) interfaces abstract classes

CSE 143. Computer Programming II

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

CSE 143. Lecture 7: Linked List Basics reading: 16.2

ITI Introduction to Computing II

Array Based Lists. Collections

ITI Introduction to Computing II

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

Java Primer. CITS2200 Data Structures and Algorithms. Topic 0

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

ITI Introduction to Computing II

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

ITI Introduction to Computing II

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

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

Last class. -More on polymorphism -super -Introduction to interfaces

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

Object Oriented Programming. Java-Lecture 11 Polymorphism

Interfaces, collections and comparisons

Topic 7: Algebraic Data Types

ITI Introduction to Computing II

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

CSE 143X. Accelerated Computer Programming I/II

Use the scantron sheet to enter the answer to questions (pages 1-6)

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

Building Java Programs

Lecture Notes Chapter #9_b Inheritance & Polymorphism

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

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

Chapter 14 Abstract Classes and Interfaces

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

Inheritance Sort in ascending order. Reusability 5 Sort Take The 4 Order 12,10,5,4. Class. Use this class to define a new class

Inheritance and Interfaces

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

CS-202 Introduction to Object Oriented Programming

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

EXAMINATIONS 2011 Trimester 2, MID-TERM TEST. COMP103 Introduction to Data Structures and Algorithms SOLUTIONS

Linked Lists. References and objects

Inheritance, Polymorphism, and Interfaces

Java Object Oriented Design. CSC207 Fall 2014

Abstract Classes Interfaces

Java interface Lecture 15

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

Abstract Classes and Interfaces

Lecture 36: Cloning. Last time: Today: 1. Object 2. Polymorphism and abstract methods 3. Upcasting / downcasting

List ADT. Announcements. The List interface. Implementing the List ADT

Inheritance and Polymorphism

Java Comparable interface

Homework 6. Yuji Shimojo CMSC 330. Instructor: Prof. Reginald Y. Haseltine

Inheritance Abstraction Polymorphism

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

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

Rules and syntax for inheritance. The boring stuff

F I N A L E X A M I N A T I O N

Distributed Systems Recitation 1. Tamim Jabban

index.pdf January 21,

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

CS 151. Linked Lists, Recursively Implemented. Wednesday, October 3, 12

More on inheritance CSCI 136: Fundamentals of Computer Science II Keith Vertanen Copyright 2014

G51PRG: Introduction to Programming Second semester

JAVA MOCK TEST JAVA MOCK TEST II

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

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

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

CS/ENGRD 2110 SPRING 2018

Polymorphism: Inheritance Interfaces

Lecture Notes Chapter #9_c Abstract Classes & Interfaces

COP 3330 Final Exam Review

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

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

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

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

Inheritance, polymorphism, interfaces

MIT AITI Lecture 18 Collections - Part 1

26. Interfaces. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

Polymorphism: Interfaces and Iteration. Fundamentals of Computer Science

Java Collections Framework: Interfaces

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

25. Interfaces. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

Advanced Placement Computer Science. Inheritance and Polymorphism

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

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

Making New instances of Classes

CSE 143 Lecture 22. The Object class; Polymorphism. read slides created by Marty Stepp and Ethan Apter

Object-Oriented Programming More Inheritance

We are on the GUI fast track path

Introductory Programming Inheritance, sections

Lecture 4: Extending Classes. Concept

Lecture Outline. Parametric Polymorphism and Java Generics. Polymorphism. Polymorphism

Transcription:

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 String tostring() { return "circle of area " + area(); 2 1

Rectangle public class Rectangle { private double length; private double width; public Rectangle(double length, double width) { this.length = length; this.width = width; public double area() { return length * width; public String tostring() { return "rectangle of area " + area(); 3 Square public class Square { private double length; public Square(double length) { this.length = length; public double area() { return length * length; public String tostring() { return "square of area " + area(); 4 2

Shape client code import java.util.*; public class ShapeTest { public static void main(string[] args) { Object[] data = {new Square(12), new Rectangle(15, 3.2), new Circle(8.4), new Circle(1.5), new Square(8.7), new Rectangle(7.2, 3.2), new Square(2.4), new Circle(3.7), new Circle(7.9); for (Object s : data) { System.out.println(s); System.out.println(); Arrays.sort(data); for (Object s : data) { System.out.println(s); Recall that the Object class is at the top of the inheritance hierachy 5 Comparable? Client code crashes when trying to sort the elements ÏÏException in thread "main" java.lang.classcastexception: Square cannot be cast to java.lang.comparable ÏÏ Ï at java.util.arrays.mergesort(arrays.java:1144) ÏÏ Ï at java.util.arrays.mergesort(arrays.java:1155) ÏÏ Ï at java.util.arrays.sort(arrays.java:1079) ÏÏ Ï at ShapeTest.main(ShapeTest.java:13) Sort method tries to cast object to Comparable so it can call compareto method. BTW, notice that Java uses merge sort to sort! 6 3

Implementing Comparable public class Square implements Comparable<Square> {... Writing the compareto method public int compareto(square other) { return area() - other.area(); The previous method has the wrong return type: public int compareto(square other) { return (int)(area() - other.area()); 7 Writing compareto This previous method also fails! If the difference is between -1 and 1. Casting to int rounds it to 0. Correct answer: public int compareto(square other) { double difference = area() - other.area(); if (difference < 0) { return -1; else if (difference == 0) { return 0; else { // difference > 0 return 1; 8 4

Client code still crashes ÏÏException in thread "main" java.lang.classcastexception: Rectangle cannot be cast to Square ÏÏ Ï at Square.compareTo(Square.java:1) ÏÏ Ï at java.util.arrays.mergesort(arrays.java:1144) ÏÏ Ï at java.util.arrays.mergesort(arrays.java:1155) ÏÏ Ï at java.util.arrays.sort(arrays.java:1079) ÏÏ Ï at ShapeTest.main(ShapeTest.java:13) Differs from previous error message: Square cannot be cast to java.lang.comparable Currently Squares and Rectangles are not related to each other. 9 Shape interface public interface Shape { public class Square implements Comparable<Shape> {... public int compareto(shape other) {... public class Rectangle implements Comparable<Shape> {... public class Circle implements Comparable<Shape> {... 10 5

Area undefined? Square.java:5: cannot find symbol ÏÏ Ïsymbol : method area() ÏÏ Ïlocation: interface Shape Notice the "location". public interface Shape { public double area(); 11 More ClassCastExceptions! Ï Exception in thread "main" java.lang.classcastexception: Rectangle cannot be cast to Shape ÏÏ Ï at Square.compareTo(Square.java:1) ÏÏ Ï at java.util.arrays.mergesort(arrays.java:1144) ÏÏ Ï at java.util.arrays.mergesort(arrays.java:1155) ÏÏ Ï at java.util.arrays.sort(arrays.java:1079) ÏÏ Ï at ShapeTest.main(ShapeTest.java:13) We never said that Rectangles were Shapes public class Rectangle implements Shape, Comparable<Shape> { But all Shapes are to be Comparable anyway Notice that interfaces extend other interface (not implements!) public interface Shape extends Comparable<Shape> { public class Rectangle implements Shape { 12 6

Modified client code import java.util.*; public class ShapeTest { public static void main(string[] args) { Shape[] data = {new Square(12), new Rectangle(15, 3.2), new Circle(8.4), new Circle(1.5), new Square(8.7), new Rectangle(7.2, 3.2), new Square(2.4), new Circle(3.7), new Circle(7.9); for (Shape s : data) { System.out.println(s); System.out.println(); Arrays.sort(data); for (Shape s : data) { System.out.println(s); 13 Removing redundancy Each shape class has the exact same compareto method! public interface Shape extends Comparable<Shape> { public double area(); public int compareto(shape other) { double difference = area() - other.area(); if (difference < 0) { return -1; else if (difference == 0) { return 0; else { // difference > 0 return 1; 14 7

Interfaces and methods Methods in interfaces cannot have bodies. Ï Shape.java:4: interface methods cannot have body ÏÏ Ï public int compareto(shape other) { ÏÏ Ï ^ ÏÏ Ï1 error Change to class and implement Comparable Ï public class Shape implements Comparable<Shape> { public double area(); public int compareto(shape other) { double difference = area() - other.area(); if (difference < 0) { return -1; else if (difference == 0) { return 0; else { // difference > 0 return 1; 15 Missing method body ϼ ÏShape.java:2: missing method body, or declare abstract ÏÏ Ï public double area(); ÏÏ Ï ^ ÏÏ Ï1 error What about this? public double area() { return 0; // dummy value Hacks are never good ideas Declare class as abstract. public abstract class Shape implements Comparable<Shape> { public abstract double area(); public int compareto(shape other) {... public class Rectangle extends Shape { // Shape is no longer an interface 16 8

Continuum of classes Concrete class All methods defined Abstract class Some methods defined Interface No methods defined 17 Abstract and interfaces Normal classes that claim to implement an interface must implement all methods of that interface: public class Empty implements Shape { // error Abstract classes can claim to implement an interface without writing its methods; subclasses must implement the methods. public abstract class Empty implements Shape { // ok public class Child extends Empty { // error 18 9

Object creation Since abstract classes have some undefined methods, they cannot be instantiated. (Recall that interfaces cannot be instantiated too!) Shape s = new Shape(); // illegal Shape s = new Rectangle(20, 30); // ok! 19 Abstract class vs. interface Why do both interfaces and abstract classes exist in Java? An abstract class can do everything an interface can do and more. So why would someone ever use an interface? Answer: Java has single inheritance. can extend only one superclass can implement many interfaces Having interfaces allows a class to be part of a hierarchy (polymorphism) without using up its inheritance relationship. 20 10

Last redundancy tostring() method is a bit redundant Put name and tostring() in abstract superclass: public abstract class Shape implements Comparable<Shape> { private String name; public Shape(String name) { this.name = name; public abstract double area(); public int compareto(shape other) {... public String tostring() { return name + " of area " + area(); 21 New constructors public Circle(double radius) { super("cicle"); this.radius = radius; public Rectangle(double length, double width) { super("rectangle"); this.length = length; this.width = width; public Square(double length) { super("square"); this.length = length; 22 11

Linked vs. array lists We have implemented two collection classes: ArrayIntList index 0 1 2 3 value 42-3 17 9 LinkedIntList front data next 42 data next -3 data next 17 data next 9 They have similar behavior, implemented in different ways. We should be able to treat them the same way in client code. 23 An IntList interface // Represents a list of integers. public interface IntList { public void add(int value); public void add(int index, int value); public int get(int index); public int indexof(int value); public boolean isempty(); public boolean contains(int value); public void remove(int index); public void set(int index, int value); public int size(); public class ArrayIntList implements IntList {... public class LinkedIntList implements IntList {... 24 12

An abstract list class // Superclass with common code for a list of integers public abstract class AbstractIntList implements IntList { public void add(int value) { add(size(), value); public boolean contains(int value) { return indexof(value) >= 0; public boolean isempty() { return size() == 0; public class ArrayIntList extends AbstractIntList {... public class LinkedIntList extends AbstractIntList {... 25 Putting it all together // Superclass with common code for a list of integers public abstract class AbstractList<E> implements List<E> { public void add(e value) { add(size(), value); public boolean contains(e value) { return indexof(value) >= 0; public boolean isempty() { return size() == 0; public class ArrayList<E> extends AbstractList<E> {... public class LinkedList<E> extends AbstractList<E> {... See: http://download.oracle.com/javase/6/docs/api/java/util/abstractlist.html 26 13