CS305j Introduction to Computing Inheritance and Polymorphism 1 Topic 26 Introduction to Inheritance and Polymorphism "One purpose of CRC cards [a design.

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

Object Oriented Programming
SUMMARY: abstract classes and interfaces 1 Make a class abstract so instances of it cannot be created. Make a method abstract so it must be overridden.
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 9: Inheritance and Interfaces.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
CSE 143 Lecture 14 Interfaces; Abstract Data Types (ADTs) reading: 9.5, 11.1; 16.4 slides created by Marty Stepp
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
Building Java Programs Interfaces, Comparable reading: , 16.4, 10.2.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-4: Interfaces reading: self-check: exercises: #11.
Sadegh Aliakbary Sharif University of Technology Fall 2011.
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
CSC 142 Computer Science II Zhen Jiang West Chester University
Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Peyman Dodangeh Sharif University of Technology Fall 2014.
1 Building Java Programs Chapter 9: Inheritance and Interfaces These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be.
CS305j Introduction to Computing Classes 1 Topic 23 Classes – Part I "A 'class' is where we teach an 'object' to behave." -Rich Pattis Based on slides.
Salman Marvasti Sharif University of Technology Winter 2015.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
CSE 143 Lecture 6 Interfaces; Complexity (Big-Oh) reading: 9.5, 11.1, slides created by Marty Stepp
EE 422C Interfaces Day 5. 2 Announcements SVN has Project 2. –Partly due next week. –SVN update to get it in your repository. See Piazza for Grocery List.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Java Polymorphism. What we have learned Polymorphism is one of the three very powerful and useful mechanisms offered by OOP. What are the other two?
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Interfaces, Abstract Classes, and Polymorphism. What Is an Interface? An interface is the set of public methods in a class Java provides the syntax for.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
Copyright 2009 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-1.
Abstract Classes. Recall We have the ability to create hierarchies of classes. Good design practice suggests that we move common methods as high as possible.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
Building Java Programs Interfaces reading: , 16.4.
1 More About Derived Classes and Inheritance Chapter 9.
Lecture 21: Interfaces and Abstract classes
Advanced Programming in Java
Modern Programming Tools And Techniques-I
Chapter 15 Abstract Classes and Interfaces
Inheritance ITI1121 Nour El Kadri.
Interfaces.
Lecture 9-2: Interacting with the Superclass (super);
Road Map Inheritance Class hierarchy Overriding methods Constructors
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Interfaces EE 422C.
Chapter 9: Polymorphism and Inheritance
Interfaces CS163 Fall 2018.
Week 6 Object-Oriented Programming (2): Polymorphism
CSE 143 Lecture 6 Interfaces; Complexity (Big-Oh)
Advanced Programming Behnam Hatami Fall 2017.
Based on slides by Alyssa Harding & Marty Stepp
Chapter 14 Abstract Classes and Interfaces
CSE 142 Lecture Notes Inheritance, Interfaces, and Polymorphism
CSE 142 Lecture Notes Defining New Types of Objects, cont'd.
Chapter 11 Inheritance and Polymorphism
slides created by Marty Stepp
Lecture 8-2: Object Behavior (Methods) and Constructors
Introduction to Methods and Interfaces
Presentation transcript:

CS305j Introduction to Computing Inheritance and Polymorphism 1 Topic 26 Introduction to Inheritance and Polymorphism "One purpose of CRC cards [a design tool] is to fail early, to fail often, and to fail inexpensively. It is a lot cheaper to tear up a bunch of cards that it would be to reorganize a large amount of source code. " - Cay Horstmann Based on slides for Building Java Programs by Reges/Stepp, found at

CS305j Introduction to Computing Inheritance and Polymorphism 2 Managing Complexity  software development: The practice of conceptualizing, designing, constructing, documenting, and testing large- scale computer programs. (a.k.a. software engineering)  Challenges: –managing lots of programmers –dividing work –avoiding redundant code (wasted effort) –finding and fixing bugs –testing –maintenance (between 50% and 90% of cost)  Code reuse: writing code once and reusing it in different applications and programs.

CS305j Introduction to Computing Inheritance and Polymorphism 3 Categories  Often we categorize objects in the real world starting with a general category and then becoming more specific. –Let's think about people, human beings. What things does every human being have? What does every human being know how to do? –We could draw a diagram of these things. Something like this: data behaviors Person name age favorite movie talk play

CS305j Introduction to Computing Inheritance and Polymorphism 4 Subcategories  Within the broad range of people, let's talk about a specific group: members of the University –What new attributes and behaviors are there? –Let's assume that all members are people, and draw them as a subcategory of persons, as shown to the right –Members of the University add some new abilities and attributes. UTEID work –Employees perform some of the original person's abilities differently. talk about the University –Notice we don't repeat things from Person Person name age favorite movie talk play Member of the University UTEID what I owe books checked out talk (about UT) work check out book

CS305j Introduction to Computing Inheritance and Polymorphism 5 More categorization  We can add more categories. –Each category has the ability of the ones above it. –Categories may add new abilities, or change the way in which they perform existing abilities. Person Member of the University FacultyStudentStaff Tenure Track LecturerGradUndergrad

CS305j Introduction to Computing Inheritance and Polymorphism 6 Categories as code  Let's implement a class for a person public class Person { private String favoriteMovie; public void talk(){ System.out.println("Hi!"); } public void play(){ System.out.println("Watching " + favoriteMovie); }

CS305j Introduction to Computing Inheritance and Polymorphism 7 Subcategory, first try  The class for Member has much in common with Person: public class UniversityMember { private String favoriteMovie; private String UTEID; public void talk(){ System.out.println("Hi!"); } public void play(){ System.out.println("Watching " + favoriteMovie); } public void who(){ System.out.println("My UTEID is " + UTEID); } } What do computer scientists look for?

CS305j Introduction to Computing Inheritance and Polymorphism 8 Inheritance  inherit: To gain all the data fields and methods from another class, and become a child of that class. –superclass: The class from which you inherit. –subclass: The class that inherits.  Inheritance, general syntax: public class extends { –Example: public class UniversityMember extends Person { –Each member object now automatically: has a talk and play method can be treated as a Person by any other code (e.g. an Employee could be stored as an element of a Person[] )

CS305j Introduction to Computing Inheritance and Polymorphism 9 Subclass with inheritance  A better version of the UniversityMember class: public class UniversityMember extends Person{ private String UTEID; public void who(){ System.out.println("My UTEID is " + UTEID); } } –We only write the portions that are unique to each (data) type. –If we have a UniversityMember object we can call all methods from Person and UniversityMember

CS305j Introduction to Computing Inheritance and Polymorphism 10 Another example: Shapes  Imagine that we want to add a class Square. –A square is just a rectangle with both sides the same length. –If we wrote Square from scratch, its behavior would largely duplicate that from Rectangle. –We'd like to be able to create a Square class that absorbs behavior from the Rectangle class, to remove the redundancy. square rectangle

CS305j Introduction to Computing Inheritance and Polymorphism 11 Square and Rectangle  Differences between square code and rectangle code: –Square only needs one size parameter to its constructor. Square sq = new Square(3, 7, 4); rather than Rectangle rect = new Rectangle(2, 9, 13, 6); –Squares print themselves differently with toString. "Square[x=3,y=7,size=4]" rather than "Rectangle[x=2,y=9,width=13,height=6]"

CS305j Introduction to Computing Inheritance and Polymorphism 12 Inheritance  Reminder: inheritance, general syntax: public class extends {  Let's declare that all squares are just special rectangles: public class Square extends Rectangle {  Each Square object now automatically: –has an x, y, width, and height data field –has a getArea, getPerimeter, draw, toString, intersection method –can be treated as a Rectangle by any other code (e.g. a Square could be stored as an element of a Rectangle[] )

CS305j Introduction to Computing Inheritance and Polymorphism 13 Inheritance and constructors  We want Squares to be constructed with only an (x, y) position and a size (because their width and height are equal). –But internally, the Square has x/y/width/height data fields, which all need to be initialized. –We can make a Square constructor that uses the Rectangle constructor to initialize all the data fields.  Syntax for calling superclass's constructor: super( ); –Example: public class Square extends Rectangle { public Square(int x, int y, int size) { super(x, y, size, size); } Each Square object is initialized with its width and height equal. The size parameter to the Square constructor provides the value for the width and height parameters to the superclass Rectangle constructor.

CS305j Introduction to Computing Inheritance and Polymorphism 14 Overriding methods  We don't want to inherit the toString behavior, because Squares print themselves differently than rectangles.  override: To write a new version of a method in a subclass, replacing the superclass's version. –If Square declares its own toString method, it will replace the Rectangle toString code when Squares are printed. public String toString() { return "Square[x=" + this.getX() + ",y=" + this.getY() + ",size=" + this.getWidth() + "]"; } We have to say, for example, this.getX() instead of this.x because the data fields are private (can only actually be modified inside the Rectangle class). We'll use this.getWidth() as our size, but the height would also work equally well.

CS305j Introduction to Computing Inheritance and Polymorphism 15 Relatedness of types  We've previously written several 2D geometric types such as Circle and Rectangle. –We could add other geometric types such as Triangle.  There are certain attributes or operations that are common to all shapes. –perimeter - distance around the outside of the shape –area - amount of 2D space occupied by the shape  Every shape has these attributes, but each computes them differently.

CS305j Introduction to Computing Inheritance and Polymorphism 16 Shape area, perimeter  Rectangle –area= w h –perimeter= 2w + 2h  Circle –area=  r 2 –perimeter= 2  r  Triangle –area= (1/2) b h –perimeter= side1 + side2 + side3

CS305j Introduction to Computing Inheritance and Polymorphism 17 Common behavior  Let's write methods getPerimeter, getArea, and draw for all our shape types.  We'd like to be able to treat different shapes in the same way, insofar as they share common behavior, such as: –Write a method that prints any shape's area and perimeter. –Create an array of shapes that could hold a mixture of the various shape objects. –Return a method that could return a rectangle, a circle, a triangle, or any other shape we've written. –Make a DrawingPanel display many shapes on screen.

CS305j Introduction to Computing Inheritance and Polymorphism 18 Interfaces  interface: A type that consists only of a set of methods, that classes can pledge to implement. –Interfaces allow us to specify that types have common behavior, by declaring that they implement a common interface. –The interface type can be used to refer to an object of any type that implements the interface's methods. –A method may accept a parameter of an interface type, or return a value of an interface type. In these cases, a value of any implementing type may be passed / returned.

CS305j Introduction to Computing Inheritance and Polymorphism 19 Interface syntax  Let's declare that certain types of objects can be Shapes, and that every Shape type has a getArea and getPerimeter method. public interface Shape { public double getArea(); public double getPerimeter(); public void draw(Graphics g); }  Interface declaration, general syntax: public interface { ; } –A method header specifies the name, parameters, and return type of the method. –The header is followed by a ; and not by { } The implementation is not specified, because we want to allow each shape to implement its behavior in its own way.

CS305j Introduction to Computing Inheritance and Polymorphism 20 Implementing an interface  implement an interface: To declare that your type of objects will contain all of the methods in a given interface, so that it can be treated the same way as any other type in the interface.  Implementing an interface, general syntax: public class implements {... } –Example: We can specify that a class is a Shape. public class Circle implements Shape {... }

CS305j Introduction to Computing Inheritance and Polymorphism 21 Diagrams of interfaces  We draw arrows upward from the classes to the interface(s) they implement. –There is an implied superset-subset relationship here; e.g., all Circles are Shapes, but not all Shapes are Circles. –This kind of picture is also called a UML class diagram.

CS305j Introduction to Computing Inheritance and Polymorphism 22 Interface requirements  Since the Shape interface declares a getArea and getPerimeter method, this mandates that any class wishing to call itself a Shape must have these two methods.  If we write a class that claims to be a Shape but doesn't have both of these methods, it will not compile. –Example: public class Banana implements Shape { } C:\foo\Banana.java:1: Banana is not abstract and does not override abstract method getArea() in Shape public class Banana implements Shape { ^

CS305j Introduction to Computing Inheritance and Polymorphism 23 How interfaces are used  We can write a method that accepts an object of an interface type as a parameter, or returns an interface type. –Example: public static void printInfo(Shape s) { System.out.println("The shape: " + s); System.out.print("area: " + s.getArea()); System.out.println(", perimeter: " + s.getPerimeter()); System.out.println(); } –Any object that implements the interface may be passed as the parameter to this method.  polymorphism: The ability to run the same code on objects of many different types.

CS305j Introduction to Computing Inheritance and Polymorphism 24 Using polymorphism  The following code uses the printInfo method from the previous slide, with shapes of 2 different types. public static void main(String[] args) { Circle circ = new Circle(new Point(3, 7), 6); Rectangle rect = new Rectangle(10, 20, 4, 7); printInfo(circ); printInfo(rect); } Output: The shape: Circle[center=(3, 7),radius=6] area: , perimeter: The shape: Rectangle[x=10,y=20,width=4, height=7] area: 28.0, perimeter: 22.0

CS305j Introduction to Computing Inheritance and Polymorphism 25 Arrays of interface type  We can create an array of an interface type, and store any object implementing that interface as an element. Circle circ = new Circle(new Point(3, 7), 6); Rectangle rect = new Rectangle(10, 20, 4, 7); Triangle tri = new Triangle(new Point(), new Point(7, 9), new Point(15, 12)); Shape[] shapes = {circ, tri, rect}; for (int i = 0; i < shapes.length; i++) { printInfo(shapes[i]); } –Each shape executes its appropriate behavior when it is passed to the printInfo method, or when getArea or getPerimeter is called on it.