lecture notes – inheritance and polymorphism (ch 9-10) yonglei tao
TRANSCRIPT
![Page 1: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/1.jpg)
Lecture Notes – Inheritance and Polymorphism (Ch 9-10)
Yonglei Tao
![Page 2: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/2.jpg)
Inheritance An “is a” relationship between classes
Generalization and specialization Software reuse
Employee
ManagerWorker
![Page 3: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/3.jpg)
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; } }
![Page 4: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/4.jpg)
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;
}
![Page 5: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/5.jpg)
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
![Page 6: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/6.jpg)
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
![Page 7: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/7.jpg)
Inheritance Hierarchies
![Page 8: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/8.jpg)
Multiple Inheritance
1-8
![Page 9: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/9.jpg)
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
![Page 10: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/10.jpg)
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
![Page 11: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/11.jpg)
An Example // in class Employeepublic abstract double calcBiWeeklyPay ();
// in class Workerpublic double calcBiWeeklyPay () { return hours * basePay; }
// in class Managerpublic double calcBiWeeklyPay () { return basePay / 26; }
// in client codeEmployee 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 () );}
![Page 12: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/12.jpg)
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
![Page 13: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/13.jpg)
Final Classes and Methods
public final class A {... // cannot be extended
}
public class B {final void f () { ... } // cannot be
overridden....
}
Improve security and optimization
![Page 14: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/14.jpg)
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
![Page 15: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/15.jpg)
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 wordNone of the methods inan interface are given
a definition (body)
A semicolon immediatelyfollows each method header
![Page 16: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/16.jpg)
Interfaces
public class CanDo implements Doable{ public void doThis () { // whatever }
public void doThat () { // whatever }
// etc.}
implements is areserved word
Each method listedin Doable is
given a definition
![Page 17: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/17.jpg)
Interfaces
![Page 18: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/18.jpg)
Interface and Its Implementationpublic 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; }
…}
![Page 19: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/19.jpg)
DataSet for Measurable Objectspublic 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
![Page 20: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/20.jpg)
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"); }}
![Page 21: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/21.jpg)
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
![Page 22: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/22.jpg)
The Object Class
All classes extend Object, directly or indirectly, explicitly or implicitly, and therefore inherit its methods
![Page 23: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/23.jpg)
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
![Page 24: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/24.jpg)
Type Conversion Implicit conversion
intVar = charExpr;floatVar = intExpr;doubleVar = floatExpr;
Worker w = new Worker ();Employee p = w;
Explicit conversionchar ch = (char) anInt; // anInt = 65long num = (long) aDouble; // aDouble = 7.99
![Page 25: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/25.jpg)
Explicit Conversion Employee p; Worker w = new Worker(“Tom”, 7.95, 40); Manager m = new Manager(“John”, 36000);
… // either p = w or p = mw = p; ?
public void aMethod ( Employee p ) {if ( p instanceof Worker )
Worker w = (Worker) p;…
}}
![Page 26: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/26.jpg)
Class Shapepublic 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(); }}
![Page 27: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/27.jpg)
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;
}
}
![Page 28: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/28.jpg)
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; } }
![Page 29: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/29.jpg)
Class Square
public class Square extends Rectangle {
public Square ( double side ) { super ( side, side ); }
}
![Page 30: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/30.jpg)
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; } }
![Page 31: Lecture Notes – Inheritance and Polymorphism (Ch 9-10) Yonglei Tao](https://reader036.vdocuments.site/reader036/viewer/2022062519/5697bfe91a28abf838cb6e64/html5/thumbnails/31.jpg)
// 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?