Inheritance and Polymorphism Recitation 04/10/2009 CS 180 Department of Computer Science, Purdue University.

Slides:



Advertisements
Similar presentations
Introduction to OOP with Java 4th Ed, C. Thomas Wu
Advertisements

METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 8 Inheritance and.
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.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Inheritance Java permits you to use your user defined classes to create programs using inheritance.
Inheritance and Polymorphism CS180 Fall Definitions Inheritance – object oriented way to form new classes from pre-existing ones –Superclass The.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 13  Inheritance and Polymorphism  Access Modifiers  Abstract.
1 Lecture 3 Inheritance. 2 A class that is inherited is called superclass The class that inherits is called subclass A subclass is a specialized version.
Slides prepared by Rose Williams, Binghamton University Chapter 7 Inheritance.
Inheritance Recitation - 02/22/2008 CS 180 Department of Computer Science, Purdue University.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Polymorphism.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 13 Inheritance and Polymorphism Animated Version.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Inheritance and Polymorphism Recitation – 10/(16,17)/2008 CS 180 Department of Computer Science, Purdue University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Abstract Superclasses and Abstract Methods When.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Chapter 7 - Generalization/Specialization and Inheritance1 Chapter 7 Generalization/Specialization and Inheritance.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Taken from slides of Starting Out with C++ Early Objects Seventh Edition.
Intro to OOP with Java, C. Thomas Wu
Features of Object Oriented Programming Lec.4. ABSTRACTION AND ENCAPSULATION Computer programs can be very complex, perhaps the most complicated artifact.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
CS200 Algorithms and Data StructuresColorado State University Part 4. Advanced Java Topics Instructor: Sangmi Pallickara
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
Method signature Name and parameter list public static void test() public static int test() => Syntax error, Duplicate method test You cannot declare more.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 13 Inheritance and Polymorphism.
©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 13 Inheritance and Polymorphism.
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Peyman Dodangeh Sharif University of Technology Fall 2014.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter Chapter 13 Inheritance and Polymorphism.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Inheritance Chapter 7. Outline Inheritance Basics Programming with Inheritance Dynamic Binding and Polymorphism.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Inheritance and Polymorphism.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Intro to OOP with Java, C. Thomas Wu Inheritance and Polymorphism
Modern Programming Tools And Techniques-I
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Inheritance and Polymorphism
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
CSC 143 Inheritance.
Inheritance Basics Programming with Inheritance
Inheritance and Polymorphism
CS18000: Problem Solving and Object-Oriented Programming
Computer Programming with JAVA
Java – Inheritance.
Java Inheritance.
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Chapter 9 Carrano Chapter 10 Small Java
Chapter 11 Inheritance and Polymorphism Part 1
Chapter 11 Inheritance and Encapsulation and Polymorphism
Programming in C# CHAPTER 5 & 6
Presentation transcript:

Inheritance and Polymorphism Recitation 04/10/2009 CS 180 Department of Computer Science, Purdue University

2 Reminders Project 7 is due next Wednesday.

3 Introduction Recall:  Inheritance allows data and methods to be inherited by a subclass.  Polymorphism simplifies code by automatically using the appropriate method for a given object/type.

4 Inheritance A subclass is a specialization of the class it inherits from. The common behavior is implemented once in the superclass and automatically inherited by the subclasses. Consider the example of a roster of students with different grading for graduates and undergrads.

5 Overriding A derived class may override an inherited method Simply define a method with the same method header.  An overridden method cannot change the return type!  Can be prevented with final Note Difference: A subclass may overload any method by using the same name, but different signature.

6 The Java Inheritance Hierarchy private: data members and methods are accessible only to instances of the class. protected: visible to instances of the class and individual descendant instances. public: accessible to all

7 Inheritance and Constructors Constructors are not inherited. Default constructors are made iff no others found A call to the superclass constructor, super(), must be the first line of a constructor  It is automatically added if not present You may optionally call some other constructor of the base class,  e.g.: super( “some string” ); super also has other meanings

8 Super keyword It can also be used to call a method of the parent class:  e.g.: super.methodA(); This can be useful to:  Call an overridden method  Access data members of the parent

Example 1 Consider a college record-keeping system with records about students, faculty and staff. All these specific groups are sub-classes of the class Person.

Example 1, cont. class Person { private String name; public Person() { name = “no name”; } public Person(String _name) { name = _name; } public void setName(String) { … } public String getName() { … } public void output() { System.out.println(name); }

Example 1, cont. class Student is a subclass of class Person and class Person is called the superclass. public class Student extends Person{ private int studentNumber; public Student(String _name, int _num){ super(_name); studentNumber = _num; } // override the method in Person class public void output() { System.out.println(name); System.out.println(studentNumber); } //more methods not in Person class … }

12 Polymorphism Polymorphism allows a single variable to refer to objects from different subclasses in the same inheritance hierarchy For example, if Cat and Dog are subclasses of Pet, then the following statements are valid: Pet myPet; myPet = new Dog();... myPet = new Cat();

13 Dynamic Binding At compile time, the version of a polymorphic method to be executed is unknown.  Determined at run-time by the class of the object This is called dynamic (late) binding

14 Object Type Consider the inheritance hierarchy: Object ← A ← B An instance of B is also an instance of A and Object.  Instances of class B can be used where objects of class A can be used.  The relationship is one way (thus the arrows) A reference of type A can hold an object of type B. It can only be treated like an instance of A unless cast.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 15 The instanceof Operator The instanceof operator can help us discover the class of an object at runtime. The following code counts the number of undergraduate students. int undergradCount = 0; for (int i = 0; i < numberOfStudents; i++) { if ( roster[i] instanceof UndergraduateStudent ) { undergradCount++; }

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 16 Definition: Abstract Class An abstract class is a class  defined with the modifier abstract OR  that contains an abstract method OR  that does not provide an implementation of an inherited abstract method An abstract method is a method with the keyword abstract, and it ends with a semicolon instead of a method body.  Private methods and static methods may not be declared abstract. No instances can be created from an abstract class.

©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 17 Inheritance versus Interface Interfaces are like a contract to share or guarantee behavior Inheritance is used to share common code when one class is a specialized form of another.

Example 2 Animal BirdMammalFish OwlBatPenguinGiraffeWhaleSharkSalmon Flyer Swimmer

Example 2 Our animals: public class Owl {…} public class Penguin {…} public class Bat {…} public class Giraffe {…} public class Whale {…} public class Shark {…} public class Salmon {…}

Example 2 Create appropriate superclasses: public class Animal {…} public class Bird {…} public class Mammal {…} public class Fish {…} public class Owl {…} public class Penguin {…} public class Bat {…} public class Giraffe {…} public class Whale {…} public class Shark {…} public class Salmon {…}

Example 2 Connect the hierarchy: public class Animal {…} public class Bird extends Animal {…} public class Mammal extends Animal {…} public class Fish extends Animal {…} public class Owl extends Bird {…} public class Penguin extends Bird {…} public class Bat extends Mammal {…} public class Giraffe extends Mammal {…} public class Whale extends Mammal {…} public class Shark extends Fish {…} public class Salmon extends Fish {…}

Example 2 Add in appropriate interfaces at the highest levels: public class Animal {…} public class Bird extends Animal {…} public class Mammal extends Animal {…} public class Fish extends Animal implements Swimmer {…} public class Owl extends Bird implements Flyer {…} public class Penguin extends Bird {…} public class Bat extends Mammal implements Flyer {…} public class Giraffe extends Mammal {…} public class Whale extends Mammal implements Swimmer {…} public class Shark extends Fish {…} public class Salmon extends Fish {…}

Example 2 Make appropriate classes abstract: abstract public class Animal {…} abstract public class Bird extends Animal {…} abstract public class Mammal extends Animal {…} abstract public class Fish extends Animal implements Swimmer {…} public class Owl extends Bird implements Flyer {…} public class Penguin extends Bird {…} public class Bat extends Mammal implements Flyer {…} public class Giraffe extends Mammal {…} public class Whale extends Mammal implements Swimmer {…} public class Shark extends Fish {…} public class Salmon extends Fish {…}

Example 2 - Quiz Which are valid instantiations? Animal a = new Animal(); Animal b = new Fish(); Animal c = new Flyer(); Mammal d = new Bat(); Fish e = new Swimmer(); Swimmer f = new Shark(); Flyer g = new Owl(); Swimmer h = new Whale(); Swimmer i = new Fish(); abstract public class Animal {…} abstract public class Bird extends Animal {…} abstract public class Mammal extends Animal {…} abstract public class Fish extends Animal implements Swimmer {…} public class Owl extends Bird implements Flyer {…} public class Penguin extends Bird {…} public class Bat extends Mammal implements Flyer {…} public class Giraffe extends Mammal {…} public class Whale extends Mammal implements Swimmer {…} public class Shark extends Fish {…} public class Salmon extends Fish {…}

Timer and TimerTask Timer  scheduleAtFixedRate(TimerTask task, long delay, long period) task: task to be scheduled. delay: delay in milliseconds before task is to be executed for the first time perid: time in milliseconds between successive task executions

Timer and TimerTask TimerTask  Inherit this class  Override the run() method Put everything you want to be executed into this method.

Timer and TimerTask Example public class TimerTest { private Timer timer; private TimerTask task; public TimerTest(TimerTask task) { this.timer = new Timer(); this.task = task; } public void start(int delay, int internal) { timer.scheduleAtFixedRate(task, delay * 1000, internal * 1000); } public static void main(String[] args) { TimerTask task1 = new MyTask(“ Job 1"); TimerTask task2 = new MyTask("Job 2"); TimerTest tt1 = new TimerTest(task1); tt1.start(1,3); TimerTest tt2 = new TimerTest(task2); tt2.start(1,1); } class MyTask extends TimerTask { private String jobName; //override public void run() { System.out.println(jobName); } public MyTask(String jobName) { } this.jobName = jobName; } Inherit the TimerTask Polymorphism Override the abstract method in the class TimerTask. delay * 1000 (ms) = delay (sec)