Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.

Slides:



Advertisements
Similar presentations
Object Oriented Programming with Java
Advertisements

Lecture 5: Interfaces.
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance, part 2: Subclassing COMP 401, Fall 2014 Lecture 8 9/11/2014.
9. Inheritance 9.1 Subclasses 9.2 Polymorphism 9.3 Abstract Classes 9.4 Modifiers and Access 9.6 Object-Oriented Design with Use Cases and Scenarios.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Creating Classes from Other Classes Chapter 2. 2 Chapter Contents Composition Adapters Inheritance Invoking constructors from within constructors Private.
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
Programming Languages and Paradigms Object-Oriented Programming.
Question of the Day  Write valid mathematical equation using: one addition operator (‘+’) one equality operator (‘=’)  Should have equal values.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Recap (önemli noktaları yinelemek) from last week Paradigm Kay’s Description Intro to Objects Messages / Interconnections Information Hiding Classes Inheritance.
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.
1 Object-Oriented Software Engineering CS Interfaces Interfaces are contracts Contracts between software groups Defines how software interacts with.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
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.
What is inheritance? It is the ability to create a new class from an existing class.
APCS Java AB 2004 Review of CS1 and CS2 Review for AP test #1 Sources: 2003 Workshop notes from Chris Nevison (Colgate University) AP Study Guide to go.
Tuc Goodwin  Object and Component-Oriented Programming  Classes in C#  Scope and Accessibility  Methods and Properties  Nested.
Week 14 - Monday.  What did we talk about last time?  Introduction to C++  Input and output  Functions  Overloadable  Default parameters  Pass.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Inheritance and Access Control CS 162 (Summer 2009)
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Object Oriented Programming
CIS 270—Application Development II Chapter 8—Classes and Objects: A Deeper Look.
Interfaces About Interfaces Interfaces and abstract classes provide more structured way to separate interface from implementation
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Classes, Interfaces and Packages
Access Specifier. Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member.
Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.
Presented by Ted Higgins, SQL Server DBA An Introduction to Object – Oriented Programming.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Java Programming, Second Edition Chapter Three Using Methods, Classes, and Objects.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Part 1: Composition, Aggregation, and Delegation Part 2: Iterator COMP 401 Fall 2014 Lecture 10 9/18/2014.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Inheritance and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Interface.
Java Programming Language
CSE 1020:Inheritance Mark Shtern.
Chapter 14 Abstract Classes and Interfaces
Presentation transcript:

Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014

Polymorphism Poly = many, morph = forms General principle of providing access to an abstraction or method in many forms – Idea is that different forms “fit” different contexts – Goal of the underlying functionality is the same. In OO programming, principle is evident in a number of different places. – Constructor overloading – Method overloading

Constructors What happens when you don’t define a constructor. – Default constructor with no arguments. Creates new object with all fields set to default value – Numeric fields set to 0 – Boolean fields set to false – String, Array, and any other sort of reference value field set to null. lec7.ex1

An aside on putting more than one class in a file. A Java file can only have one “public” class. – A class marked public can be imported into other code. – Must match file name One or more “non-public” classes in a Java file can also be defined – Only available to code in the same package. – Does not have to match file name – Often used to define classes that are related to a public class in that file.

Constructor Overloading Can define multiple versions of the constructor. – Distinguished from each other by type and number of parameters Must be some difference otherwise the compiler won’t be able to tell them apart. – When you use the constructor, the right one will be chosen based on the parameters provided. – Note that once you define a constructor that takes parameters, the implicit, default no-argument constructor is no longer automatically available. lec7.ex2

Constructor Chaining Common pattern is to “chain” one constructor off of another. – To do this, the first line of code in the constructor must be the this keyword used as a function with parameters. – The matching constructor is called first and allowed to execute. – Then any subsequent code is executed. – Can chain multiple constructors one on to another lec7.ex3

Method Overloading Regular methods can also be overloaded – Same method name defined more than once. Return type may or may not be the same. – But usually is. Method type must be the same. – Instance method or static class method – Access modifier Parameter list must somehow be different – Again, this is how the compiler knows which one is meant. – Either different in number or type (or both) One version can call another – No restrictions on when – No special syntax lec7.ex4, lec7.ex5

Why Overload? Provides access to constructor / method in a more context specific way. Limitations of overloading – Does not handle the case when you have two different situations that aren’t distinguished by the number or type of parameters being passed.

Recap of Interfaces A “contract” for behavior. – Defined by a set of method signatures. – Acts as a data type. – No implementation. Specific classes implement the interface

Song and Video as Media public interface Media { int getLengthInSeconds(); double getLengthInMinutes(); int getRating(); void setRating(int new_rating); String getName(); } public class Song implements Media {.... public class Video implements Media {.... We expect Song and Video to have methods matching those specified in Media.

Is-A and casting A class that implements an interface creates an “is-a” relationship between class data type and the interface data type. – A implements B => A “is a” B Song is a Media Video is a Media Casting allowed across an is-a relationship. 11 Song s = new Song(); Media m; m = (Media) s; Video v = new Video(); Media m; m = (Media) v; Video v = new Video(); Song s; s = (Song) v;

Inheritance What is inheritance in real life? – Characteristics / resources that you receive from your parents Get these automatically. Part of who you are. Similar idea in object-oriented programming. – In Java, concept of inheritance applied to both interfaces and classes. Both signaled by the keyword “extends” Similar in concept, but details are distinctly different. – Class inheritance more complex.

Extending Interfaces Adds methods to the contract. – Original: parent interface, super interface – New: subinterface, child interface, extended interface Created by using the “extends” keyword. public interface CompressedMedia extends Media { int getCompressedSize(); int getUncompressedSize(); Media uncompress(); }

Extension Creates Hierarchy Is-A relationship is transitive up the hierarchy. Media Compressed Media extends public class Song implements CompressedMedia {... Methods for both must be provided. Song s = new Song(); CompressedMedia cm = (CompressedMedia) s; Media m = (Media) s; Song s2 = (Song) m; OK because s “is a” Compressed Media OK because s is a Media by virtue of extension. Casting from interface back to specific object type is allowed, but at runtime, if the object’s type does not actually match, a runtime exception will be thrown.

Extension vs. Composition Interface extension appropriate when additional methods make no sense without methods of the parent interface. Alternatively, can compose multiple interfaces together as facets of an object.

Extension vs. Composition public interface Compressed { int getCompressedSize(); int getUncompressedSize(); Media uncompress(); } public interface Media { int getLengthInSeconds(); double getLengthInMinutes(); int getRating(); void setRating(int new_rating); String getName(); } public class Song implements Compressed, Media {... Instead of extending Media, Compressed is a separate interface and Song implements both. Song s = new Song(); Media m = (Media) s; Compressed c = (Compressed) s; Song “is a” Media AND Song “is a” Compressed.

Subinterface Multiple Inheritance Multiple inheritance for interfaces is allowed. – A subinterface can extend more than one existing interface. – In this case, just a union of all methods declared in all of the parent interfaces. Plus, of course, any additional ones added by the subinterface. lec7.ex6

Motivating Enumerations Often need to model part of an object as one value from a set of finite choices – Examples: Suite of a playing card Day of week Directions of a compass One approach is to use named constants – lec7.ex7 Drawbacks of this approach – No type safety – No value safety

Simple Java Enumerations General syntax: access_type enum EnumName {symbol, symbol,...}; Example: – public enum Genre {POP, RAP, JAZZ, INDIE, CLASSICAL} Enumeration name acts as the data type for the enumerated values. – Enumerated values available as EnumName.symbol as in: Genre.POP Outside of the class – Fully qualified name required as in: Song.Genre.POP Symbol names don’t have to all caps, but that is traditional lec7.ex8

Enumerations in Interfaces Enumerations can be defined within an interface. – Useful when enumeration is related to the interface as an abstraction and will be needed within any specific implementation.

Not so simple enumerations Java enumerations are actually much more powerful than this. Check out this tutorial for more: um-in-java-example-tutorial.html um-in-java-example-tutorial.html – Also posted on course resources page in Piazza.