Inheritance and Interfaces

Similar documents
Inheritance and Polymorphism

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

CS 251 Intermediate Programming Inheritance

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

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

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Inheritance, Polymorphism, and Interfaces

CS-202 Introduction to Object Oriented Programming

Java Object Oriented Design. CSC207 Fall 2014

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

Motivations. Chapter 13 Abstract Classes and Interfaces

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

Introduction to Inheritance

Inheritance. Finally, the final keyword. A widely example using inheritance. OOP: Inheritance 1

Chapter 13 Abstract Classes and Interfaces. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Lecture 5: Inheritance

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

Polymorphism. return a.doublevalue() + b.doublevalue();

OVERRIDING. 7/11/2015 Budditha Hettige 82

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

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

Polymorphism: Inheritance Interfaces

Inheritance, polymorphism, interfaces

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

CS 112 Programming 2. Lecture 10. Abstract Classes & Interfaces (1) Chapter 13 Abstract Classes and Interfaces

8. Polymorphism and Inheritance

C12a: The Object Superclass and Selected Methods

Object Oriented Programming. Java-Lecture 11 Polymorphism

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

COMP1008 An overview of Polymorphism, Types, Interfaces and Generics

The class Object. Lecture CS1122 Summer 2008

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

Interfaces. James Brucker

Chapter 5 Object-Oriented Programming

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Chapter 13 Abstract Classes and Interfaces

Inheritance and Polymorphism

CS313D: ADVANCED PROGRAMMING LANGUAGE

Inheritance & Abstract Classes Fall 2018 Margaret Reid-Miller

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

Chapter 10 Classes Continued. Fundamentals of Java

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

Programming in C# Inheritance and Polymorphism

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

CMSC 132: Object-Oriented Programming II

Distributed Systems Recitation 1. Tamim Jabban

Inheritance. Transitivity

This week. Tools we will use in making our Data Structure classes: Generic Types Inheritance Abstract Classes and Interfaces

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

COS226 - Spring 2018 Class Meeting # 13 March 26, 2018 Inheritance & Polymorphism

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

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

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

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

Inheritance and Interfaces

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

Inheritance. OOP: Inheritance 1

Inheritance -- Introduction

ITI Introduction to Computing II

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

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

CIS 110: Introduction to computer programming

CS 520 Theory and Practice of Software Engineering Fall 2018

CS 110 Practice Final Exam originally from Winter, Instructions: closed books, closed notes, open minds, 3 hour time limit.

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

ITI Introduction to Computing II

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Programming using C# LECTURE 07. Inheritance IS-A and HAS-A Relationships Overloading and Overriding Polymorphism

More about inheritance

Inheritance (Part 2) Notes Chapter 6

Super-Classes and sub-classes

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

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Polymorphism. Arizona State University 1

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

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

Chapter 14 Abstract Classes and Interfaces

Inf1-OP. Classes with Stuff in Common. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein.

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

Practice for Chapter 11

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Inf1-OP. Inheritance. Volker Seeker, adapting earlier version by Perdita Stevens and Ewan Klein. March 12, School of Informatics

INHERITANCE. Spring 2019

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

Distributed Systems Recitation 1. Tamim Jabban

Inheritance & Polymorphism

Comparing Objects 3/14/16

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

TeenCoder : Java Programming (ISBN )

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

Introduction to Computation and Problem Solving

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

CMSC131. Inheritance. Object. When we talked about Object, I mentioned that all Java classes are "built" on top of that.

CST242 Object-Oriented Programming Page 1

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

ITI Introduction to Computing II

Polymorphism. Agenda

CS313D: ADVANCED PROGRAMMING LANGUAGE

CMSC 341. Nilanjan Banerjee

Transcription:

Inheritance and Interfaces what is inheritance? examples & Java API examples inheriting a method overriding a method polymorphism Object tostring interfaces Ex: sorting and Comparable interface Inheritance and Interfaces [Bono] 1

Announcements Time to get started on PA3 Inheritance and Interfaces [Bono] 2

Inheritance terminology: a subclass (or derived class) inherits from a superclass (or base class) derived class is a specialization of the base class add or change functionality reuse code and interface can use derived objects in place of base objects. inheritance models IS-A or IS-A-KIND-OF relationship Some examples of this: Dog IS-A Mammal Manager IS-A Employee Ford IS-A Car Inheritance and Interfaces [Bono] 3

Inheritance: what it isn t review: inheritance models IS-A inheritance is not for HAS-A Examples of HAS-A: Car HAS Wheels ArrayList HAS Elements use containment for HAS-A a superclass is not a generic type e.g., List vs. ListofInts vs. ListofStrings Java generics does this: ArrayList<Integer>, ArrayList<String> Inheritance and Interfaces [Bono] 4

Some examples of inheritance Calendar Shape Employee GregorianCalendar Circle Triangle Rectangle Manager JComponent CarComponent CoinSimComponent Inheritance and Interfaces [Bono] 5

Inheriting a method From lab2: GregorianCalendar date = ; date.set( ); Gregorian calendar is a subclass of Calendar: public class GregorianCalendar extends Calendar { set method is inherited from Calendar GregorianCalendar has no method definition for set Inheritance and Interfaces [Bono] 6

Overriding a method Making a subclass and overriding a method from the superclass public class CarComponent extends JComponent {... public void paintcomponent(graphics g) { // code to draw a car on the screen Inheritance and Interfaces [Bono] 7

Not method overriding method overloading: public class String { public String substring(int begin, int end) { // return the substring that goes from the // specified index to the end of the string public String substring(int begin) {... Inheritance and Interfaces [Bono] 8

Not method overriding Method signature different from the one defined in the superclass: public class CarComponent extends JComponent {... public void paintcomponent(int length) { // code to draw a car on the screen public void paintcomponent(graphics g, int x) { // code to draw a car on the screen Inheritance and Interfaces [Bono] 9

Not method overriding Two unrelated classes with the same method name and params: // no inheritance this paintcomponent is // unrelated to JComponent s version public class Foo { public void paintcomponent(graphics g) {...... Inheritance and Interfaces [Bono] 10

Some characteristics of inheritance Can assign up the type hierarchy safely: JComponent comp = new CarComponent( ); or myframe.add(new CarComponent( )); Inheritance and Interfaces [Bono] 11

Swing using CarComponent Java Swing framework code doesn t know about CarComponent Java Swing code can later safely call: component.paintcomponent(g); CarComponent s paintcomponent gets called (run-time type) Inheritance and Interfaces [Bono] 12

Polymorphism Varying what actual method is called at run-time via method overriding: polymorphism Overriding / polymorphism is type-safe All JComponent subclasses have to either inherit paintcomponent or override it. Inheritance and Interfaces [Bono] 13

How is it type-safe? public class CarComponent extends JComponent { // overridden from JComponent: public void paintcomponent(graphics g) { // CarComponent-specific function: public Wheels getwheels() { (Reminder: Foo defines paintcomponent, it s not a subclass of JComponent) myframe.add(new Foo()); // 1 JComponent comp = new CarComponent(); // 2 comp.getwheels(); // 3 CarComponent carcomp = (CarCompenent) comp; // 4 carcomp.getwheels(); // 5 Inheritance and Interfaces [Bono] 14

Object class Object is the highest class in the hierarchy Every other Java class is a subclass of Object (Might be a few levels down a hierarchy.) Means all objects have some methods in common: public class Object { public String tostring() { public boolean equals(object other) {... Inheritance and Interfaces [Bono] 15

tostring method Defined for all objects String + operator uses it automatically to convert your object type to a string: System.out.println("My account: " + bankaccount); Calls Object tostring behind the scenes Default (Object) version prints weird stuff (hashcode) Convention: override tostring to print out all the field names and values for debugging purposes Most Java classes override tostring to do this. Ex: Person class Inheritance and Interfaces [Bono] 16

Example of defining tostring public class Person { private String name; private int favoritenumber; private Point geocoord; public String tostring() { return "Person[name=" + name + ",favoritenumber=" + favoritenumber... + ",geocoord=" + geocoord // calls Point tostring +"] ; Inheritance and Interfaces [Bono] 17

Interfaces interface and implements are Java keywords Like a superclass, but has no implementation of its own: no instance variables no method bodies Defines the headers for methods an implementing class must implement class that implements the interface may also have other methods may implement multiple interfaces simultaneously Inheritance and Interfaces [Bono] 18

Ex: implementing an interface Part of Java library is Comparable interface: implementing this interface means you can compare two objects of your type (less than, greater than)... using a method called compareto. Some Java classes are Comparable, e.g., String, GregorianCalendar Example: make Student class comparable Inheritance and Interfaces [Bono] 19

Comparable interface A class is Comparable if it implements the compareto method. public interface Comparable<Type> { int compareto(type other); Inheritance and Interfaces [Bono] 20

Comparable interface (cont.) Implementing comparable means clients can compare two objects of your type String implements Comparable: a.compareto(b); returns a value < 0 if a < b returns a value > 0 if a > b returns 0 if a = b What do we need to do to make our class comparable: Declare that the class implements Comparable Implement compareto method for our class Inheritance and Interfaces [Bono] 21

Implementing Comparable class Student implements Comparable<Student> { private String firstname; private String lastname; private int score; public int compareto(student b) { int lastdiff = lastname.compareto(b.lastname); if (lastdiff!= 0) { return lastdiff; else { // last names are equal return firstname.compareto(b.firstname); Inheritance and Interfaces [Bono] 22

Sorting example Want to use Arrays.sort Sort is overloaded for int[], double[], etc.: int[] myarr = ; Arrays.sort(myArr); Uses < to compare two elements. But how to use sort on array of your own object types? Student[] studarr = ; Arrays.sort(studArr); problem: < not defined for Student What does it mean for one student to be less than another? Inheritance and Interfaces [Bono] 23

Sorting example (cont.) We can define what less-than means for Students But, we don't want to have to implement a sort routine ourselves. And then reimplement for the next element-type we want to sort, etc. Solution: Sort has a version that works if our element-type implements the Comparable interface: class Arrays {... public static void sort(comparable[] arr); Inheritance and Interfaces [Bono] 24

Sorting students (cont.) What code do you need to write? 1. Make Student class implement Comparable part of that is to implement compareto 2. Now can use Java s sort method on an array of Students: Student[] studarr = ;... Arrays.sort(studArr); Arrays.sort calls the compareto method we defined Inheritance and Interfaces [Bono] 25

Code examples on-line In code directory for today s lecture: Person class (with tostring) and tester program that shows the limits of when tostring will automatically get invoked. compareex subdirectory: Student class that implements Comparable Comparator for two Student objects (part of readings: Special Topic 14.4) Example prog that uses both of these to sort an array of Student s two different ways. Inheritance and Interfaces [Bono] 26

Why extend a Java class or implement a Java interface? A common use of inheritance is to extend classes or implement interfaces defined by some library: This is a way to plug in application specific code so other parts of the library can call our method without having to know anything about our exact class. Form of reusability. Today s examples: can reuse all the Swing GUI code with our own GUI app (Swing is an application framework) can reuse the fast Java sort code to sort our own data Inheritance and Interfaces [Bono] 27