Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.

Slides:



Advertisements
Similar presentations
Overriding CMPS Overriding Recall, a method in a child class overrides a method in the parent class, if it has the same name and type signature.
Advertisements

Lecture 5: Interfaces.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
OOP: Inheritance By: Lamiaa Said.
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
Comp 249 Programming Methodology Chapter 7 - Inheritance – Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
(C) 2010 Pearson Education, Inc. All rights reserved. Java™ How to Program, 8/e.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
Inheritance, part 2: Subclassing COMP 401, Fall 2014 Lecture 8 9/11/2014.
© 2006 Pearson Addison-Wesley. All rights reserved9 A-1 Chapter 9 Advanced Java Topics (inheritance review + Java generics)
ITEC200 – Week03 Inheritance and Class Hierarchies.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
OOP in Java Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
ISE 582: Web Technology for Industrial Engineers University of Southern California Department of Industrial and Systems Engineering Lecture 4 JAVA Cup.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
OOP in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Computer Science I Inheritance Professor Evan Korth New York University.
Inheritance. Types of Inheritance Implementation inheritance means that a type derives from a base type, taking all the base type’s member fields and.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
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.
Computer Science and Engineering College of Engineering The Ohio State University Lot More Inheritance and Intro to Design Patterns Lecture 12.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
Specialization and Inheritance Chapter 8. 8 Specialization Specialized classes inherit the properties and methods of the parent or base class. A dog is.
1 COSC3557: Object-Oriented Programming Haibin Zhu, Ph. D. Associate Professor of CS, Nipissing University.
What is inheritance? It is the ability to create a new class from an existing class.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance - Polymorphism ITI 1121 Nour El Kadri.
C# F 1 CSC 298 Object Oriented Programming (Part 1)
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
Chapter 10: Introduction to Inheritance. Objectives Learn about the concept of inheritance Extend classes Override superclass methods Call constructors.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
CS2102: Lecture on Abstract Classes and Inheritance Kathi Fisler.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
1 C# - Inheritance and Polymorphism. 2 1.Inheritance 2.Implementing Inheritance in C# 3.Constructor calls in Inheritance 4.Protected Access Modifier 5.The.
Exceptions Lecture 11 COMP 401, Fall /25/2014.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Polymorphism and access control. RHS – SOC 2 What is polymorphism? In general: the ability of some concept to take on different forms In Java: the ability.
Class Inheritance Part II: Overriding and Polymorphism Corresponds with Chapter 10.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Web Design & Development Lecture 9
Inheritance and Polymorphism
Java Programming Language
Java – Inheritance.
Java Inheritance.
Chapter 14 Abstract Classes and Interfaces
Presentation transcript:

Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014

Subclassing So Far A subclass inherits implementation details from its superclass – Fields Direct access to public and protected fields No direct access to private fields – Methods Access to public and protected methods No access to private methods Subclass constructors – Should call superclass constructor with super() as first line. Or, chain to a different constructor Or, rely on implicit call to super() constructor with no parameters.

Subclass Method Polymorphism Subclass can overload methods in superclass. – Remember, overloading is providing a different version of an existing method. An example of polymorphism Method signature is different in some way. – lec09.ex1

Overriding Methods A subclass can “override” a super class method by providing its own definition. – Method signature must be the same. – Original method is visible from subclass i.e., public, protected, or package-level access lec09.ex2

@Override directive So what’s with the funny line that Eclipse includes when generating a stub? – Known as a compiler “directive”. Completely optional, but useful – Indicates that the method is intended to override a superclass method. Compiler will complain if it does not detect a visible superclass or interface method with the same method signature. Helpful when you misspell a method name or attempt to override a method not visible to the subclass. lec09.ex3

Class Polymorphism Previously introduced the idea of “is-a” relationships – Between a class and interfaces implemented. – Between a class and its superclass hierarchy. This is also an example of polymorphism – Covariance Treating an instance of a subclass as a reference typed as the parent class. This can be typed checked at compile type. – Contravariance Treating a reference typed as the parent class as an instance of a subclass. Contravariance can not be type checked in advance at compile time. Fails if the object is actually “invariant” with respect to the subclass. lec09.ex4, lec09.ex4main – Also demonstrates protected base class constructor

A Covariant Conundrum Problem: – What should happen when an overridden method is called on a covariant reference? class A { public int m() {return 0;} } class B extends A { public int m() {return 1;} } class C extends B { public int m() {return 2;} } C c_obj = new C(); B b_obj = (B) c_obj; A a_obj = (A) c_obj; System.out.println(c_obj.m()); System.out.println(b_obj.m()); System.out.println(a_obj.m()); What should these lines print?

Solution 1: Non-virtual methods Let type of reference dictate which method definition is used. class A { public int m() {return 0;} } class B extends A { public int m() {return 1;} } class C extends B { public int m() {return 2;} } C c_obj = new C(); B b_obj = (B) c_obj; A a_obj = (A) c_obj; System.out.println(c_obj.m()); System.out.println(b_obj.m()); System.out.println(a_obj.m()); If methods are non-virtual then these lines expected to print: 2 1 0

Solution 2: Virtual methods Use method defined by the actual type of object (even if reference is covariant) class A { public int m() {return 0;} } class B extends A { public int m() {return 1;} } class C extends B { public int m() {return 2;} } C c_obj = new C(); B b_obj = (B) c_obj; A a_obj = (A) c_obj; System.out.println(c_obj.m()); System.out.println(b_obj.m()); System.out.println(a_obj.m()); With virtual methods, these lines expected to print: 2

Virtual Methods Different OOP languages choose to solve this problem in different ways. – C++, C# Default is non-virtual solution. Programmer can force virtual solution by marking a method with a special “virtual” keyword – Java Methods are always virtual. No special keyword needed. lec09.ex5

A virtual problem Drawback to the “always virtual” approach. – Consider the situation in which a subclass just needs a method to “do just a little more”. In other words, wants to execute a method as defined in the superclass and then tweak the result. Or maybe do something in advance of executing a method as defined in the superclass. – Because methods are always virtual, casting this reference to superclass in order to get to method as defined by the superclass won’t work. lec09.ex6 (won’t work)

It’s a bird, it’s a plane, it’s… … the super keyword. The super keyword provides exactly this ability to invoke methods on an instance as it is understood at the superclass. – Think of it as a version to “this” that is restricted to just what is provided by the superclass. Note: Only goes up one level in class hierarchy – Essentially suspending “virtualness” of methods. lec09.ex7

Whence inheritance Related classes with common internals – Common fields used as part of methods with a common implementation. – Note, not just common behavior Specialization of existing classes after the fact.

Inheritance Recap Subinterfacing – Adding methods to create a new “contract” Subclassing – Inherits fields and methods from parent class Visibility controlled by access modifier – Adds subclass specific fields and methods – Constructor relationship – Overloading parent methods Version of a method provided in subclass with different signatures than the version(s) in the parent class. – Overriding parent methods Subclass methods with same signature as in parent class. Always virtual – super keyword provides a mechanism to call parent class version of a method

Using inheritance Example starts with several related classes that are implemented independently. – BlackBear – PolarBear – Python – Robin – lec09.ex8.v1

Common behavior Refactor common behaviors into a common parent interface. – Animal interface – lec09.ex8.v2

Common object state Refactor common object fields into a common parent class – AnimalImpl Pull common fields id and location to here Need to make protected in order to allow subclass access. – lec09.ex8.v3

Common implementation Refactor common method implementations into parent class. – Use overriding if subclasses need to do something special or different. – AnimalImpl Constructor in parent class used by subclass constructor to initialize common fields at this level. getID() and getLocation() moved here Common portion of move() put here – Subclass-specific override of move – Calls common portion through super keyword – lec09.ex8.v4

Common behavior with uncommon implementation Notice speak() is a common behavior. – So we want it to be part of Animal interface That way if we can have a reference to an Animal object and ask it to speak() without having to know what subclass it is. But no common implementation. – Each subclass of animal will have a different way of speaking. – No good default or commonalities in way of speaking that can be specified at parent class.

Abstract Classes and Methods Parent class has no meaningful implementation of a method. – But method is part of an interface implemented by parent class – Expect subclass to provide it. – In these situations, we never expect (or want) the parent class to be instantiated directly. We always make new objects using a subclass. Syntax – Use “abstract” modifier when declaring parent class – Declare any methods that must be provided by subclass in parent Add “abstract” modifier to method signature. Follow signature with semicolon instead of method definition

Example Revisited AnimalImpl – Declare implementation of Animal here where it belongs since AnimalImpl is matching implementation. – Declare AnimalImpl as abstract Prevents direct instantiation – Declare speak() method as abstract No common implementation, but needs to be declared here as part of common interface. Declaring as abstract forces subclass to override. lec09.ex8.v5

Repeat Exercise with Bears lec09.ex8.v6 – Draws out common bear behavior into Bear interface and common bear implementation in BearImpl Bear extends Animal – Adds getColor() BearImpl extends AnimalImpl – Provides lumber(), trek(), move(), and speak(). – Declared abstract because subclass must provide getColor()