Inheritance and Polymorphism

Similar documents
Announcements. Final exam. Course evaluations. Saturday Dec 15 10:20 am -- 12:20 pm Room: TBA

Chapter 13. Inheritance and Polymorphism. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Inheritance, Polymorphism, and Interfaces

24. Inheritance. Java. Fall 2009 Instructor: Dr. Masoud Yaghini

22. Inheritance. Java. Summer 2008 Instructor: Dr. Masoud Yaghini

Inheritance and Polymorphism

Java Object Oriented Design. CSC207 Fall 2014

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

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

CS 251 Intermediate Programming Inheritance

Chapter 10 Inheritance and Polymorphism. Dr. Hikmat Jaber

Chapter 14 Abstract Classes and Interfaces

Object Oriented Programming. Java-Lecture 11 Polymorphism

OVERRIDING. 7/11/2015 Budditha Hettige 82

Chapter 5. Inheritance

Programming in C# Inheritance and Polymorphism

CS1150 Principles of Computer Science Objects and Classes

Chapter 10 Classes Continued. Fundamentals of Java

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

CS 112 Programming 2. Lecture 06. Inheritance & Polymorphism (1) Chapter 11 Inheritance and Polymorphism

Instance Members and Static Members

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

Inheritance and Polymorphism. CS180 Fall 2007

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

Computer Science II (20073) Week 1: Review and Inheritance

Inheritance and Polymorphism

Lecture Notes Chapter #9_b Inheritance & Polymorphism

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

Practice for Chapter 11

25. Generic Programming

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

CS-202 Introduction to Object Oriented Programming

Inheritance. Chapter 7. Chapter 7 1

What is Inheritance?

Inheritance (continued) Inheritance

8. Polymorphism and Inheritance

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

C++ Important Questions with Answers

ITI Introduction to Computing II

Polymorphism and Inheritance

Chapter 5 Object-Oriented Programming

Upcasting. Taking an object reference and treating it as a reference to its base type is called upcasting.

IST311. Advanced Issues in OOP: Inheritance and Polymorphism

EKT472: Object Oriented Programming. Overloading and Overriding Method

Programming Languages and Techniques (CIS120)

Inheritance and object compatibility

Example: Count of Points

ITI Introduction to Computing II

Inheritance and Interfaces

PROGRAMMING LANGUAGE 2

Chapter 1: Introduction to Computers, Programs, and Java

CST242 Object-Oriented Programming Page 1

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

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

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Inheritance -- Introduction

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Java Class Design. Eugeny Berkunsky, Computer Science dept., National University of Shipbuilding

Programming in Java, 2e Sachin Malhotra Saurabh Choudhary

core Advanced Object-Oriented Programming in Java

More Relationships Between Classes

Inheritance, and Polymorphism.

Advanced Object-Oriented. Oriented Programming in Java. Agenda. Overloading (Continued)

Inheritance Motivation

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

Polymorphism. Chapter 4. CSC 113 King Saud University College of Computer and Information Sciences Department of Computer Science. Dr. S.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

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

Comp 249 Programming Methodology

Constructor. Liang, Introduction to Java Programming, Tenth Edition, (c) 2013 Pearson Education, Inc. All rights reserved.

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

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

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Object Orientated Programming Details COMP360

Arrays Classes & Methods, Inheritance

First IS-A Relationship: Inheritance

Chair of Software Engineering Java and C# in Depth

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Class, Variable, Constructor, Object, Method Questions

Polymorphism. Agenda

ITI Introduction to Computing II

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

ITI Introduction to Computing II

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

Data Abstraction. Hwansoo Han

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

Data Structures and Other Objects Using C++

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

Chapter 11: Inheritance

Data Structures (list, dictionary, tuples, sets, strings)

Chapter 11 Inheritance and Polymorphism

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Object-Oriented Programming

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

Inheritance & Polymorphism

Inheritance (Extends) Overriding methods IS-A Vs. HAS-A Polymorphism. superclass. is-a. subclass

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Transcription:

Inheritance and Polymorphism Recitation 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University

Project 5 Due Wed, Oct. 22 at 10 pm. All questions on the class newsgroup. Make use of lab consulting hours to clarify all questions

Overloading of Methods and Constructors Def. Overloading The ability to allow different methods or constructors of a class to share the same name. public class Point { public Point() { /* */ public Point(int x, int y) { /* */ constructor overloading public double distance(point other) { /* */ public double distance(int x, int y) { /* */ public double distance() { /* */ // method overloading

Overloading (Cont.) Which overloaded method to invoke? Resolved at compile-time with signature matching, where signature is name and parameter types. Constructors/Methods 1: Point() 2: Point(int x,int y) 3: double distance(point other) 4: double distance(int x,int y) 5: double distance() Point p1 = new Point(); // which constructor? Point p2 = new Point(10,20); p2.distance(p1); // which method? p2.distance(20,30); p2.distance();

When to Overload? When there is a common description of the functionality that fits all the overloaded methods. public class String { public String substring(int i, int j) { // base method: return substring from index i to j - 1. public String substring(int i) { // provide default argument return substring(i, length()); //

Inheritance Inheritance models the is-a relationship. If class S extends class T, then all objects of S can act-like an object of T. Only single inheritance is allowed among classes. All public and protected members of a superclass are accessible in the subclasses.

Inheritance Contd. we can build class hierarchies using the keyword extends each child (subclass) inherits all the data and methods of its parent (superclass) we can add new methods in the subclass, or override the inherited methods private data and methods are inherited, but cannot be accessed directly; protected data and methods can be accessed directly constructor methods must be invoked in the first line in a subclass constructor as a call to super

Inheritance Example Class C is a subclass of class B (its superclass) if its declaration has the form class C extends B { The subclass extends properties and methods from superclass The superclass is a generalization of the subclass

Subclass Constructors When a subclass is created, java will call the superclass constructor first super(..) must be the first statement in subclass constructor If the superclass constructor is missing, then a no-arg super() is invoked implicitly It is advised to have a default constructor defined in every class so as to be accessed by subclass constructor Can also invoke another constructor of the same class. this( ) must be the first statement.

Example of super Calls The call to super must be the first statement in the subclass constructor Example: class C extends B { public C ( ) { super(b s constructor args ); You must use the keyword super to call the superclass constructor. Invoking a superclass constructor s name in a subclass causes a syntax error.

Example on the Impact of a Superclass without no-arg Constructor Find the errors in the program? public class Apple extends Fruit { class Fruit { public Fruit(String name) { System.out.println("Fruit's constructor is invoked"); There is no default constructor in superclass

Example of this Calls public class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; public Point() { // default constructor this(0, 0); this calls are used to avoid repeating code

Execution Order of Constructors Rule: Superclass first and field initialization first Example: S x = new S(); public class S extends T { int y = 30; // third public S( ) { super(); y = 40; // fourth public class T { int x = 10; // first public T() { x = 20; // second //...

Overriding Methods Def. Overriding Refers to the introduction of an instance method in a subclass that has the same name, signature, and return type of a method declared in the superclass. Consequences Implementation of the method in the subclass replaces the implementation of the method in the superclass

Overriding Methods (Cont.) public class Person { public void writeoutput() { public class Student extends Person { public void writeoutput() { Person p = new Person(); Student s = new Student(); p.writeoutput(); // invoke method of class Person s.writeoutput(); // invoke method of class Student

Calling Overriden Methods of Superclass super can be used to call a method in the base class that has been overridden in the derived class. Example super.writeoutput(); The above line in the Student class would call the overridden writeoutput() method in the Person class. This need not be the first line of code. You cannot use super to invoke a method in some ancestor class other than the immediate base (parent) class.

Overriding Methods (Cont.) Dynamic dispatch (binding): The method to be invoked is determined at runtime by the runtime type of the object, not by the declared type (static type). class Student { public int maxcredits() { return 15; class GraduateStudent extends Student { public int maxcredits() { return 12; Student s, s1; s = new Student(); s.getmaxcredits(); // which maxcredits method? s1 = new GraduateStudent(); S1.getMaxCredits(); // which maxcredits method?

The final Modifier You can prevent a method definition from being overridden by adding the word final to the method heading. example public final void somemethod() { The method somemethod() will not be overridden in any sub-class.

Overloading Vs. Overriding public class Test { public static void main(string[] args) { A a = new A(); a.p(10); class B { public void p(int i) { public class Test { public static void main(string[] args) { A a = new A(); a.p(10); class B { public void p(int i) { class A extends B { // This method overrides the method in B public void p(int i) { System.out.println(i); class A extends B { //This method overloads method in B public void p(double i) { System.out.println(i);

Polymorphism Polymorphism allows a variable to refer to objects from different (but related by inheritance) classes. References to data or methods are correctly resolved according to the object s class. Requires that the superclass have the inherited data or method

Student with two subclasses Student settestscore Student NUM_OF_TESTS 3 coursegrade name We We will will define define three three classes: classes: Student Student GraduateStudent UndergraduateStudent gettestscore test[ ] Implementation of of computegrade is is unique unique to to each each subclass. subclass. GraduateStudent UndergraduateStudent computegrade computegrade

Creating the roster Array Student roster[ ] = new Student[40]; roster roster is is an an array array of of Student Studentobjects. roster[0] = new GraduateStudent( ); roster[1] = new UndergraduateStudent( ); roster[2] = new UndergraduateStudent( ); roster[3] = new GraduateStudent( ); roster Create Create instances instances of of Create the Create the subclasses subclasses instances of instances of of of the Student. the Student. subclasses (An subclasses (An object object of of of of Student. a Student. derived derived class class can can serve serve as as an an object object of of base base class class --Vice Vice versa versa is is WRONG) WRONG) 0 1 2 3 4 36 37 38 39 Graduate- Student Under- graduate- Student Under- graduate- Student Graduate- Student

Processing the roster Array for (int i = 0; i < numberofstudents; i++ ) { roster[i].computegrade( ); Notice how the polymorphism is used above. The particular computegrade() method to be called is dependent on value of i (dynamic binding) If roster[i] refers to a GraduateStudent, then the computecoursegrade method of the GraduateStudent class is executed. If roster[i] refers to an UndergraduateStudent, then the computecoursegrade method of the UndergraduateStudent class is executed.

Static and Dynamic Binding Binding: determining the memory addresses for jumps Static: done at compile time also called offline Dynamic: done at run time Compilation is done offline it is a separate operation done before running a program Binding done at compile time is, therefore, static Binding done at run time is dynamic also called late binding

Abstract Classes Often we want to place elements common to all subclasses in their superclass But we do not want any instances to be created from the superclass In such case, we designate the superclass as an abstract class. This is also a way to enforce existence of methods in subclasses. Abstract classes are only used as super classes

Abstract Methods Abstract methods have no body at all and just have their headers declared The only way to use an abstract class is to create a subclass that implements each abstract method It is common for an abstract class to include an abstract method that must be implemented by the sub classes. If a class includes an abstract method, then it is considered as an abstract class and must have the abstract modifier in the class declaration.

Sample Abstract Class abstract class Student {... abstract public void computegrade( );... Reserved word abstract in the class declaration. Abstract Abstract method method has has no no method method body. body. class GraduateStudent extends Student {... public void computegrade( ) { //method body comes here... Abstract Abstract method method must must be be fully fully implemented in in the the derived derived class. class.

Interfaces An interface specifies the headings for methods that must be defined for any class that implements the interface. Example -

Interfaces Contd. A class that implements an interface must implement all the methods specified by the interface. To implement an interface, a class must include the phrase implements Interface_Name at the start of the class definition example class CS180 implements Writable { implement all the method headings listed in the definition of the interface.

Abstract Class vs. Interface Abstract classes are blueprints, interfaces are contracts Interface: Here s some methods. If your class implements this interface, you must provide an implementation of each method in the interface in the class. Method headers A class can implement multiple interfaces Cannot instantiate Abstract class: Here s a blueprint for a class. If your class extends this abstract class, you can use any functionality here and add onto it, but you must fill in what I have not. Abstract method headers Methods Variables A class can extend only one class Cannot instantiate

Quiz Print the Output class Shape { void draw() { class Circle extends Shape { void draw() { System.out.println("Circle.draw()"); class Square extends Shape { void draw() { System.out.println("Square.draw()"); class Triangle extends Shape { void draw() { System.out.println("Triangle.draw()"); Shape[] s = new Shape[9]; // Fill up the array with shapes: for(int i = 0; i < s.length; i++) { if(i%2==0) s[i] = new Circle(); else if (i%3==0) s[i] = new Square(); else s[i] = new Traingle(); // Make polymorphic method calls: for(int i = 0; i < s.length; i++) s[i].draw();