Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao.

Slides:



Advertisements
Similar presentations
1 Inheritance Chapter 9. 2 Module Outcomes To develop a subclass from a superclass through inheritance To invoke the superclass ’ s constructors and methods.
Advertisements

Chapter 11 – Interfaces and Polymorphism. Chapter Goals Learn about interfaces Learn about interfaces Convert between class and interface references Convert.
Interfaces and polymorphism Chapter 9. Interfaces  Used to express operations common to more than one purpose.  Example: You want to find the maximum.
Interfaces and Polymorphism Lesson - 8. Objectives Interfaces Supertype and subtype references Polymorphism Inner classes.
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Chapter Nine: Interfaces and Polymorphism.
Computer Science A 9: 3/11. Inheritance Today: Inheritance (JC – CCJ ) I have to leave at 11am (but you can stay)
What is an Interface?? An interface is a ‘container’ which contains ONLY abstract methods. public interface Capitalizable { public abstract String outCaps()
Big Java by Cay Horstmann Copyright © 2008 by John Wiley & Sons. All rights reserved. Interfaces and Polymorphism.
Chapter 8 – Interfaces and Polymorphism Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
More Inheritance Abstract Classes Interfaces Briana B. Morrison CSE 1302C Spring 2010.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
Interfaces. Lecture Objectives To learn about interfaces To be able to convert between class and interface references To appreciate how interfaces can.
Abstract Classes.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
1 Overloading vs. Overriding b Don't confuse the concepts of overloading and overriding b Overloading deals with multiple methods in the same class with.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Abstract Classes and Interfaces Lecture 2 – 9/6/2012.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
1 Abstract Class There are some situations in which it is useful to define base classes that are never instantiated. Such classes are called abstract classes.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Interfaces and Polymorphism 9.1 Using Interfaces for Code Reuse Defining an Interface implementing an interface 9.2 Converting between Class.
What is an Interface?? An interface is a ‘class’ which contains ONLY abstract methods. public interface Capitalizable { public abstract String outCaps()
Programming With Java ICS201 University Of Hail1 Chapter 13 Interfaces.
Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract.
INTERFACES More OO Concepts. Interface Topics Using an interface Interface details –syntax –restrictions Create your own interface Remember polymorphism.
Chapter 9 Interfaces and Polymorphism. Chapter Goals To learn about interfaces To be able to convert between class and interface references To understand.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization  that can improve reusability and system elegance.
Chapter Outline What inheritance is Calling the superclass constructor Overriding superclass methods Protected members Chains of inheritance The Object.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
CHAPTER 9 INTERFACES AND POLYMORPHISM Chapter Goals: –To learn about interfaces –To be able to convert between supertype and subtype references –To understand.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Lecture 06 Java and OOP Jaeki Song. Outlines Java and OOP –Class and Object – Inheritance – Polymorphism.
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Chapter 5 Objects and Classes Inheritance. Solution Assignments 3 & 4 Review in class…..
CHAPTER 9 INTERFACES AND POLYMORPHISM. CHAPTER GOALS To learn about interfaces To be able to convert between supertype and subtype references To understand.
Programming With Java ICS201 University Of Ha’il1 Chapter 7 Inheritance.
Object Oriented Programming
Drew University1 Interfaces and Polymorphism 9.1 Developing Reusable Solutions 9.2 Converting between Types 9.3 Polymorphism Common Error 9.1 Advanced.
Chapter 6 Object-Oriented Design Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/20 The this Reference The this reference allows an object.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
1 Enhanced Class Design -- Introduction  We now examine several features of class design and organization that can improve reusability and system elegance.
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 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
1 Object-Oriented Programming Inheritance. 2 Superclasses and Subclasses Superclasses and Subclasses  Superclasses and subclasses Object of one class.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
CMSC 202 Polymorphism 2 nd Lecture. Aug 6, Topics Constructors and polymorphism The clone method Abstract methods Abstract classes.
1 More About Derived Classes and Inheritance Chapter 9.
Modern Programming Tools And Techniques-I
Inheritance ITI1121 Nour El Kadri.
Lecture Notes – Interface and Polymorphism (Ch 9-10)
Lecture Notes – Inheritance (Ch 9-10)
Interfaces and Polymorphism
Chapter 11 – Interfaces and Polymorphism
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
Presentation transcript:

Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao

Inheritance  An “is a” relationship between classes  Generalization and specialization  Software reuse Employee ManagerWorker

Extending a Class public class Employee { protected String name; protected double basePay; public double getBasePay () { return basePay; } public void setBasePay ( doule amt ) { basePay = amt; } public String toString () { return “Name: “+name+“\nPay: “+basePay; } } public class Worker extends Employee { private double hours; public double getHours() { return hours; } public void setHours( double hrs ) { hours = hrs; } public String toString () { return super.toString()+“\nHours: “+hours; } }

Constructors // in class Employee public Employee () { } public Employee (String name, double pay) { this.name = name; basePay = pay; } // in class Worker public Worker (String name, double pay, double hours) { super (name, pay); this.hours = hours; }

Overloading vs. Overriding  Method overloading  An overloaded method has a different header  Static binding  Method overriding  An overriding method has the same header although may have its own access modifier  Dynamic binding

Polymorphic References Worker w = new Worker(“Ed”, 9.25, 25); System.out.println (“Base Pay: “ + w.getBasePay()); System.out.println (w); Employee p;// a polymorphic reference p = new Worker(“Tom”, 7.95, 40); System.out.println (p); p = new Manager(“John”, 36000); System.out.println (p);  A super class reference can refer to an object of any subclass

Inheritance Hierarchies

Multiple Inheritance 1-8

Abstract Classes public abstract class Employee { protected String name; protected double basePay; … public abstract double calcBiweeklyPay (); … }  Represent an abstract concept  Cannot be instantiated  A derived class must define all of its parent’s abstract methods or itself is an abstract class

Polymorphism  A reference of a super class can refer to an object of any descendent class  Allowing objects of different classes to respond to the same method call in different ways  Benefits  No need to use conditional logic  Simplify the client code  Extensible

An Example // in class Employee public abstract double calcBiWeeklyPay (); // in class Worker public double calcBiWeeklyPay () { return hours * basePay; } // in class Manager public double calcBiWeeklyPay () { return basePay / 26; } // in client code Employee list[] = new Employee[30]; List [0] = new Worker (“Tom”, 12.5); List [1] = new Manager (“John”, 36000); List [2] = new Worker (“Ed”, 11.25); … for (int i = 0; i < list.length; i++) { System.out.print ( list[i] ); System.out.println ( list[i].calcBiWeeklyPay () ); }

Dynamic Binding Employee p; Worker w = new Worker(“Tom”, 7.95, 40); Manager m = new Manager(“John”, 36000); …// either p = w or p = m w.calcBinweeklyPay();// static/early binding m.calcBinweeklyPay(); p.calcBiweeklyPay();// dynamic/late binding  The binding of a method call to its definition is performed at runtime for a polymorphic reference

Final Classes and Methods public final class A {...// cannot be extended } public class B { final void f () {... }// cannot be overridden.... }  Improve security and optimization

Visibility  Private members are inherited by the child class, but cannot be referenced by name  Invisible to members defined in the child class  However, they may be used indirectly  through a public method of the super class

Interfaces public interface Doable { public void doThis(); public int doThat(); public void doThis2 (float value, char ch); public boolean doTheOther (int num); } interface is a reserved word None of the methods in an interface are given a definition (body) A semicolon immediately follows each method header

Interfaces public class CanDo implements Doable { public void doThis () { // whatever } public void doThat () { // whatever } // etc. } implements is a reserved word Each method listed in Doable is given a definition

Interfaces

Interface and Its Implementation public interface Measurable{ double getMeasure(); } public class Coin implements Measurable { private double value; private String name; public double getMeasure() { return value; } public String getName() { … }... } public class BankAccount implements Measurable { private double balance; public double getMeasure() { return balance; } … }

DataSet for Measurable Objects public class DataSet { private double sum; private Measurable max; private int count;... public void add(Measurable x) { sum = sum + x.getMeasure(); if (count==0 || max.getMeasure()< x.getMeasure()) max = x; count++; } public double getAverage() { return sum/count; } public Measurable getMaximum() { return max; } } A reference of an interface can refer to an object of any implementation class

public class DataSetTester { public static void main(String[] args) { DataSet bankData = new DataSet(); bankData.add(new BankAccount(0)); bankData.add(new BankAccount(10000)); bankData.add(new BankAccount(2000)); System.out.println("Average balance: " + bankData.getAverage()); System.out.println("Expected: 4000"); Measurable max = bankData.getMaximum(); System.out.println("Highest balance: " + max.getMeasure()); System.out.println("Expected: 10000"); DataSet coinData = new DataSet(); coinData.add(new Coin(0.25, "quarter")); coinData.add(new Coin(0.1, "dime")); coinData.add(new Coin(0.05, "nickel")); System.out.println("Average coin value: “ + coinData.getAverage()); System.out.println("Expected: 0.133"); max = coinData.getMaximum(); System.out.println("Highest coin value: " + max.getMeasure()); System.out.println("Expected: 0.25"); }

Interfaces vs. Classes  An interface is similar to a class, but there are several important differences: All methods in an interface are abstract; they don’t have an implementation All methods in an interface are automatically public Instance variables in an interface are always static or final  A class may implement multiple interfaces

The Object Class  All classes extend Object, directly or indirectly, explicitly or implicitly, and therefore inherit its methods

Methods of Object  String toString ()  boolean equals (Object other)  int hashCode()  Object clone()  Class getClass()  Redefine a method if the default definition is not appropriate for a derived class

Type Conversion  Implicit conversion intVar = charExpr; floatVar = intExpr; doubleVar = floatExpr; Worker w = new Worker (); Employee p = w;  Explicit conversion char ch = (char) anInt;// anInt = 65 long num = (long) aDouble;// aDouble = 7.99

Explicit Conversion Employee p; Worker w = new Worker(“Tom”, 7.95, 40); Manager m = new Manager(“John”, 36000); …// either p = w or p = m w = p;? public void aMethod ( Employee p ) { if ( p instanceof Worker ) Worker w = (Worker) p; … } }

Class Shape public abstract class Shape { private String name; public abstract double area (); public Shape( String shapeName ) { name = shapeName; } final public boolean lessThan ( Shape other ) { return area() < other.area(); } final public String toString () { return name + " of area " + area(); }

Circle Rectangle public class Rectangle extends Shape { private double length, width; public Rectangle ( double len, double wid ) { super ( "rectangle" ); length = len; width = wid; } public double area () { return length * width; }

Class Circle public class Circle extends Shape { private double radius; public Circle( double radius ) { super ( "circle" ); this.radius = radius; } public double area () { return Math.PI * radius * radius; }

Class Square public class Square extends Rectangle { public Square ( double side ) { super ( side, side ); }

public class ShapeTest { final static int MaxSize = 50; public static void main ( String[] args ) { Shape[] shapeList = new Shape [ MaxSize ]; int size = 0, choice; for ( int i = 0; i < 15; i++ ) {// object construction choice = (int) ( Math.random() * 3 ); switch ( choice ) { case 0: shapeList[size++] = new Circle( size*1.25 ); break; case 1: shapeList[size++] = new Rectangle( size+2.5, size*7.0 ); break; case 2: shapeList[size++] = new Square ( size*5.0 ); break; }

// processing of objects for ( int i = 0; i < size; i++ ) { System.out.println( shapeList[i] ); } double total = 0; for ( int i = 0; i < size; i++ ) { total += shapeList[i].area(); } System.out.println( "The total are is " + total ); } } What needs to be done if a new subclass is added?