Need to store a list of shapes, each of which could be a circle, rectangle, or triangle

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

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

Inheritance and Polymorphism. CS180 Fall 2007

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

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

CS 61B Data Structures and Programming Methodology. July 2, 2008 David Sun

Interfaces. Interfaces. Interface Animal

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

Inheritance, Polymorphism, and Interfaces

STATIC, ABSTRACT, AND INTERFACE

CS/ENGRD 2110 SPRING 2018

Introduction to Object-Oriented Programming

Polymorphism and Interfaces. CGS 3416 Spring 2018

C09: Interface and Abstract Class and Method

Inheritance and Interfaces

CS32 - Week 4. Umut Oztok. Jul 15, Umut Oztok CS32 - Week 4

C09: Interface, and Abstract Class and Method

CS 520 Theory and Practice of Software Engineering Fall 2018

106B Final Review Session. Slides by Sierra Kaplan-Nelson and Kensen Shi Livestream managed by Jeffrey Barratt

Introduction to Computation and Problem Solving

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Programming in C# Inheritance and Polymorphism

Rules and syntax for inheritance. The boring stuff

Create a Java project named week10

CS111: PROGRAMMING LANGUAGE II

Super-Classes and sub-classes

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Critique this Code. Hint: It will crash badly! (Next slide please ) 2011 Fawzi Emad, Computer Science Department, UMCP

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

Spring 2019 Discussion 4: February 11, 2019

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Informatik II (D-ITET) Tutorial 6

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

Inheritance and Polymorphism

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

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

CS 61B Discussion 4: Inheritance Fall 2018

Inheritance, polymorphism, interfaces

Introduction to Programming

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

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

CSE 143 Lecture 12 Inheritance

Abstract. 1. What is an ABSTRACT METHOD? 2. Why you would want to declare a method as abstract? 3. A non-abstract CLASS is called a concrete class

Abstract Classes and Interfaces

public UndergradStudent(String n, String m, String p) { programme = p; super(n, m);

Java Object Oriented Design. CSC207 Fall 2014

CMSC 202. Generics II

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

QUIZ. What is wrong with this code that uses default arguments?

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

Polymorphism. Arizona State University 1

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

Lecture 21: The Many Hats of Scala: OOP 10:00 AM, Mar 14, 2018

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

Interfaces. CSE 142, Summer 2002 Computer Programming 1.

Interfaces. Readings and References. Recall the discussion of ArrayLists. How can we manage lists of objects? Reading

Outline. More optimizations for our interpreter. Types for objects

Object Oriented Programming Part II of II. Steve Ryder Session 8352 JSR Systems (JSR)

CS 251 Intermediate Programming Inheritance

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

CS 520 Theory and Practice of Software Engineering Fall 2017

Overriding המחלקה למדעי המחשב עזאם מרעי אוניברסיטת בן-גוריון

Introduction to Programming Using Java (98-388)

Logistics. Final Exam on Friday at 3pm in CHEM 102

Object Oriented Design Final Exam (From 3:30 pm to 4:45 pm) Name:

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

Inheritance & Polymorphism

1.00 Lecture 14. Exercise: Plants

Object Oriented Programming (OOP) is a style of programming that incorporates these 3 features: Encapsulation Polymorphism Class Interaction

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

XC Total Max Score Grader

Chapter 14 Abstract Classes and Interfaces

COMP 110/L Lecture 20. Kyle Dewey

Question: Total Points: Score:

Object Oriented Programming

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Week 11: Class Design

Lexical Ordering and Sorting. These slides refer to interfaces.

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

CS260 Intro to Java & Android 03.Java Language Basics

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

COMP 110/L Lecture 19. Kyle Dewey

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

Informatik II. Tutorial 6. Mihai Bâce Mihai Bâce. April 5,

First IS-A Relationship: Inheritance

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

CS 11 java track: lecture 3

COMP Summer 2015 (A01) Jim (James) Young jimyoung.ca

CS2102: Lecture on Abstract Classes and Inheritance. Kathi Fisler

Brief Summary of Java

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

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

OVERRIDING. 7/11/2015 Budditha Hettige 82

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Topic 10. Abstract Classes. I prefer Agassiz in the abstract, rather than in the concrete.

Inheritance & Interfaces and Code Layout

CS 251 Intermediate Programming Methods and Classes

CS 251 Intermediate Programming Methods and More

Transcription:

CS112-2012S-23 Abstract Classes and Interfaces 1 23-0: Drawing Example Creating a drawing program Allow user to draw triangles, circles, rectanlges, move them around, etc. Need to store a list of shapes, each of which could be a circle, rectangle, or triangle Shape superclass, with Triangle, Rectangle, and Circle subclasses 23-1: Shape Class class Shape public void draw() in main --------- Shape shapes[] = new Shape[3]; shapes[0] = new Circle(); shapes[1] = new Rectangle(); class Rectangle extends Shape shapes[2] = new Circle(); public void draw() // code to draw a Rectangle for (int i = 0; i < shapes.length; i++) shapes[i].draw(); class Circle extends Shape public void draw() // code to draw a Circle 23-2: Abstract Classes Abstract Class: How do you draw a generic shape? Drawing a generic shape doesn t make sense! Does it ever make sense to instantiate a generic Shape (instead of a circle, triangle, or rectange)? No! We can make the Shape class abstract Prevents anyone from creating an instance of Shape Shape variables are OK, as long as values are Circles, Triangles, etc 23-3: Abstract Classes abstract class Shape In main ------- public abstract void draw(); Shape s1, s2, s3; // OK! class Circle extends Shape s1 = new Shape(); // NOT OK! s2 = new Circle(); // OK! // Needs to implement draw s3 = new Triangle(); // OK! class Triangle extends Shape s2.draw(); // OK! s3.draw(); // OK! // Needs to implement draw class Rectangle extends Shape // Needs to implement draw 23-4: Abstract Classes We can make a class abstract by adding the abstract modifier to the class definition Can t create instances of an abstract class If a class is abstract, we can define abstract methods

CS112-2012S-23 Abstract Classes and Interfaces 2 Use the abstract modifier on method definition Don t give the method a body (use a ; instead of a method body) Subclasses of this class will need to either implement all abstract methods, or be abstract themselves 23-5: Inheritance Heirarchies More than one way to skin a cat Classes for animals: Standard classification: Mammal, bird, reptile Functional Classification: Flying Animal, Swimming animal Walking Animal How you design your classes depends upon the problem at hand 23-6: Inheritance Heirarchies Animal Mammal Bird Reptile Bat Seal Ostrich Finch Water Snake Animal Flyer Walker Swimmer Bat Finch Ostrich Seal Water Snake 23-7: Multiple Inheritance? Might be nice to inheret from more than one thing Bat is a mammal and a flying animal Could inherit both mammalian qualities, and qualities of flying animals Likely want to override methods specific to bats, but would be nice to get as much for free as possible Java does not allow multiple inheritance C++ does, however 23-8: Multiple Inheritance? Multiple inheritance does have problems Class A defines a method foo Class B also defines a method foo Class C inherits from both A and B (multiple inheritance)

CS112-2012S-23 Abstract Classes and Interfaces 3 Which foo does class C use? Java avoids these problems by only allowing single inheritance 23-9: Interfaces Multiple inheritance can be useful Allows more than one heirarchy structure Arrange our animal classes both structurally (mammal, reptile, etc) and functionally (swims, flies, runs, etc) We can get some of the advantages of multiple inheritance from interfaces 23-10: Interfaces A java interface is essentially a promise 23-11: Interfaces Interface defines a number of methods Classes that implement the interface promise to implement all of those methods public interface Flyer public void fly(); Any class that implements Flyer needs to implement the fly method 23-12: Interfaces public interface Flyer public void fly(); public class Bat extends Mammal implements Flyer public void fly() System.out.println("I m flying"); 23-13: Interfaces public interface Comparable public int compareto(object o); Any class that implements Comparable needs to implement the compareto method (Note recent versions of Java use Generics in Comparable interface, but the basic idea is the same 23-14: Interfaces class Student implements Comparable public int studentid; public String name; public int compareto(object other) // How can we compare an Object to a Student? // Really only want to compare students to other students! // Need a way to check if "other" is really a student // If it is a student, we need to get at "student" // instance variables (studentid, name)

CS112-2012S-23 Abstract Classes and Interfaces 4 23-15: Casting (<Type>) f If f is not of type <Type>, runtime error If f is of type <Type>, we can assign to a variable of type <Type> Object o1 = new String("Hello!"); Object o2 = new Integer(3); String s; Integer i; i = o1; // Not legal! Won t even compile i = o2; // Not legal! Won t even compile s = o1; // Not legal! Won t even compile s = o2; // Not legal! Won t even compile 23-16: Casting (<Type>) f If f is not of type <Type>, runtime error If f is of type <Type>, we can assign to a variable of type <Type> Object o1 = new String("Hello!"); Object o2 = new Integer(3); String s; Integer i; i = (Integer) o1; i = (Integer) o2; s = (String) o1; s = (String) o2; // Compiles, gives runtime error // Compiles & runs OK // Compiles & runs OK // Compiles, gives runtime error 23-17: Casting Of course, we can always assign a subclass value to a superclass variable, without casting. Never gives us a runtime error If we assign a subclass value to a superclass variable, we can get the subclass value out of the variable by casting Will give us a runtime error if the superclass variable does not hold a subclass value 23-18: Interfaces class Student implements Comparable public int studentid; public String name; public int compareto(object other) // Following will cause runtime exception if we try to // compare a Student with a non-student. int otherid = ((Student) other).studentid; if (studentid < otherid) return -1; else if (studentid > otherid) return 1; else return 0; 23-19: Using Interfaces We can declare a variable of type Comparable Can assign any comparable value to type Comparable

CS112-2012S-23 Abstract Classes and Interfaces 5 Comparable c1, c2, c3; c1 = new Student(); c2 = Integer(4); // Integer class implements Comparable c3 = "Hello"; // String class does, too 23-20: Using Interfaces Creating a comparable variable seems a little silly However, write a function that takes a Comparable variable as a parameter makes perfect sense Even better, a function that takes an array of Comparable objects as an input parameter 23-21: Using Interfaces Write a method that takes as input an array of Comparable That is, we can pass in an array of anything, as long as elements of that array implement Comparable Returns the smallest element in the array 23-22: Using Interfaces Comparable minvalue(comparable array[]) Return the smallest element in the array If the array is empty, return null 23-23: Using Interfaces Comparable minvalue(comparable array[]) if (array.length == 0) return null; Comparable smallest = array[0]; for (int i = 1; i < array.length; i++) if (array[i].comparto(smallest) < 0) smallest = array[i]; return smallest; 23-24: Using Interfaces Integer intarray[] = new Integer[10]; // fill up intarray with Integers Student studentarray[] = new Student[20]; // fill up student array with Students Integer smallestinteger = smallest(intarray); // BAD!! Why? Student smalleststudent = smallest(studentarray); // BAD!! Why? 23-25: Using Interfaces Integer intarray = new Integer[10]; // fill up intarray with Integers Student studentarray = new Student[20]; // fill up student array with Students Integer smallestinteger = (Integer) smallest(intarray); Student smalleststudent = (Student) smallest(studentarray); 23-26: Sorting Want to sort an array if integers

CS112-2012S-23 Abstract Classes and Interfaces 6 23-27: Sorting Break the list into a sorted portion and an unsorted portion Repeatedly insert the next element in the unsorted portion of the list into the sorted portion of the list (exmaples on board) public static void sort(comparable data[]) for (int i = 1; i < data.length; i++) Comparable nextelem = data[i]; int j; for (j=i-1; j >= 0 && data[j].compareto(nextelem) data[j+1] = data[j]; data[j+1] = nextelem; > 0; j--) 23-28: Sorting This sorting method can sort any array of comparables Integers Strings Students 23-29: MiniLab... anything that implements the comparable interface Create an interface Audible that contains the method speak, that takes no parameters and retuns no value Create two classes Dog and Cat that both implement the Audible interface Dog speak method prints out woof Cat speak method prints out meow In a separate driver class, create an array of Audibles, fill it with Dogs and Cats, and then have each element in the array speak.