INHERITANCE AND POLYMORPHISM 1 Inheritance Definition inheritance a

  • Slides: 45
Download presentation
INHERITANCE AND POLYMORPHISM 1

INHERITANCE AND POLYMORPHISM 1

Inheritance: Definition • inheritance: a parent-child relationship between classes • allows sharing of the

Inheritance: Definition • inheritance: a parent-child relationship between classes • allows sharing of the behavior of the parent class into its child classes • one of the major benefits of object-oriented programming (OOP) is this code sharing between classes through inheritance • child class can add new behavior or override existing behavior from parent 2

Inheritance terms • superclass, base class, parent class: terms to describe the parent in

Inheritance terms • superclass, base class, parent class: terms to describe the parent in the relationship, which shares its functionality • subclass, derived class, child class: terms to describe the child in the relationship, which accepts functionality from its parent • extend, inherit, derive: become a subclass of another class 3

Inheritance in Java • in Java, you specify another class as your parent by

Inheritance in Java • in Java, you specify another class as your parent by using the keyword extends • public class Checking. Account extends Bank. Account { • the objects of your class will now receive all of the state (fields) and behavior (methods) of the parent class • constructors and static methods/fields are not inherited • by default, a class's parent is Object • Java forces a class to have exactly one parent ("single inheritance") • other languages (C++) allow multiple inheritance 4

Inheritance Example class Bank. Account { private double my. Bal; public Bank. Account() {

Inheritance Example class Bank. Account { private double my. Bal; public Bank. Account() { my. Bal = 0; } public double get. Balance() { return my. Bal; } } class Checking. Account extends Bank. Account { private double my. Interest; public Checking. Account(double interest) { } public double get. Interest() { return my. Interest; } public void apply. Interest() { } } • Checking. Account objects have my. Bal and my. Interest fields, and get. Balance(), get. Interest(), and apply. Interest() methods 5

Multiple layers of inheritance • it is possible to extend a class that itself

Multiple layers of inheritance • it is possible to extend a class that itself is a child class; inheritance chains like this can be arbitrarily deep public class Transaction. Fee. Checking. Account extends Checking. Account { private static final double FEE = 2. 00; public void charge. Fee() { withdraw(FEE); } } 6

Inheritance Hierarchies • Deeper layered chain of classes, many children extending many layers of

Inheritance Hierarchies • Deeper layered chain of classes, many children extending many layers of parents 7

"Has-a" Relationships • "Has-a" relationship: when one object contains another as a field public

"Has-a" Relationships • "Has-a" relationship: when one object contains another as a field public class Bank. Account. Manager { private List my. Accounts; //. . . } • a Bank. Account. Manager object "has-a" List inside it, and therefore can use it 8

"Is-a" relationships • "Is-a" relationships represent sets of abilities; implemented through interfaces and inheritance

"Is-a" relationships • "Is-a" relationships represent sets of abilities; implemented through interfaces and inheritance public class Checking. Account extends Bank. Account { //. . . } • a Checking. Account object "is-a" Bank. Account • therefore, it can do anything an Bank. Account can do • it can be substituted wherever a Bank. Account is needed • a variable of type Bank. Account may refer to a Checking. Account object 9

Using the account classes • Checking. Account inherits Bank. Account's methods Checking. Account c

Using the account classes • Checking. Account inherits Bank. Account's methods Checking. Account c = new Checking. Account(0. 10); System. out. println(c. get. Balance()); c. apply. Interest(); • a Bank. Account variable can refer to a Checking. Account object Bank. Account b 2 = new Checking. Account(0. 06); System. out. println(b 2. get. Balance()); • an Object variable can point to either account type Object o = new Bank. Account(); Object o 2 = new Checking. Account(0. 09); 10

Some code that won't compile • Checking. Account variable can't refer to Bank. Account

Some code that won't compile • Checking. Account variable can't refer to Bank. Account (not every Bank. Account "is-a" Checking. Account) Checking. Account c = new Bank. Account(); • cannot call a Checking. Account method on a variable of type Bank. Account (can only use Bank. Account behavior) Bank. Account b = new Checking. Account(0. 10); b. apply. Interest(); • cannot use any account behavior on an Object variable Object o = new Checking. Account(0. 06); System. out. println(o. get. Balance()); o. apply. Interest(); 11

Mixing inheritance, interfaces • It is legal for a class to extend a parent

Mixing inheritance, interfaces • It is legal for a class to extend a parent and to implement any number of interfaces public class Bank. Account { //. . . } public class Numbered. Account extends Bank. Account implements Comparable { private int my. Number; public int compare. To(Object o) { return my. Number - ((Bank. Account)o). my. Number; } } 12

Overriding behavior • Child class can replace the behavior of its parent's methods by

Overriding behavior • Child class can replace the behavior of its parent's methods by redefining them • you have already done this. . . where? public class Bank. Account { private double my. Balance; //. . public String to. String() { return get. ID() + " $" + get. Balance(); } } public class Fee. Account extends Bank. Account { private static final double FEE = 2. 00; public String to. String() { // overriding return get. ID() + " $" + get. Balance() + " (Fee: $" + FEE + ")"; } } 13

Overriding behavior example Bank. Account b = new Bank. Account("Ed", 9. 0); Fee. Account

Overriding behavior example Bank. Account b = new Bank. Account("Ed", 9. 0); Fee. Account f = new Fee. Account("Jen", 9. 0); System. out. println(b); System. out. println(f); • Output: Ed $9. 0 Jen $9. 0 (Fee: $2. 0) 14

UML class diagrams • an industry-standard way to draw pictures of your classes and

UML class diagrams • an industry-standard way to draw pictures of your classes and their relationships to each other • classes are boxes that list the fields, methods, and constructors of the type • classes that have inheritance relationships, or are tightly related to each other, are connected by arrows 15

Class Diagram: Single Class • attributes (fields) are written as access. Modifier name :

Class Diagram: Single Class • attributes (fields) are written as access. Modifier name : type where access. Modifier is one of • - for private • + for public • # for protected • example: - my. Size: int • methods are written as access. Modifier name(arg 1 : type 1, arg 2 : type 2, . . . ) : return. Type • omit the : return. Type if return. Type is void • example: + withdraw(amount : double) : boolean 16

Class diagram: inheritance • inheritance relationships • hierarchies drawn top-down with arrows from child

Class diagram: inheritance • inheritance relationships • hierarchies drawn top-down with arrows from child to parent • if parent is an interface, write its class name in << >> and draw white dashed arrows • if parent is a class, use black arrows 17

Class diagram: associations • associational relationships (how many) 2. name (what relationship the objects

Class diagram: associations • associational relationships (how many) 2. name (what relationship the objects have) 3. navigability (who has relationship with whom) 1. multiplicity 18

Class diagram: example 19

Class diagram: example 19

Access modifiers • public: visible to all other classes public class Bank. Account •

Access modifiers • public: visible to all other classes public class Bank. Account • private: visible only to the current class, its methods, and every instance (object) of its class • a child class cannot refer to its parent's private members! private String my. ID; • protected (this one's new to us): visible to the current class, and all of its child classes protected int my. Width; • package (default access; no modifier): visible to all classes in the current "package" (seen later) int my. Height; 20

Access modifier problem (pt. 1) public class Parent { private int field 1; protected

Access modifier problem (pt. 1) public class Parent { private int field 1; protected int field 2; public int field 3; private void method 1() {} public void method 2() {} protected void set. Field 1(int value) { field 1 = value; } } 21

Access modifier problem (pt. 2) public class Child extends Parent { public int field

Access modifier problem (pt. 2) public class Child extends Parent { public int field 4; public Child() { field 4 = 0; field 1++; field 2++; field 3++; method 1(); method 2(); set. Field 1(field 4); } // // Which are legal? _________ _________ } 22

Some code that won't compile public class Point 2 D { private int x,

Some code that won't compile public class Point 2 D { private int x, y; public Point 2 D(int x, int y) { this. x = x; this. y = y; } } public class Point 3 D extends Point 2 D { private int z; public Point 3 D(int x, int y, int z) { this. x = x; this. y = y; // can't do this! this. z = z; } } 23

super keyword • used to refer to superclass (parent) of current class • can

super keyword • used to refer to superclass (parent) of current class • can be used to refer to parent class's methods, variables, constructors to call them • needed when there is a name conflict with current class • useful when overriding and you want to keep the old behavior but add new behavior to it • syntax: super(args); constructor super. field. Name super. method. Name(args); // call parent’s // access parent’s field // or method 24

super example public class Bank. Account { private double my. Balance; public void withdraw(double

super example public class Bank. Account { private double my. Balance; public void withdraw(double amount) { my. Balance -= amount; } } public class Fee. Account extends Bank. Account { public void withdraw(double amount) { super. withdraw(amount); if (get. Balance() < 100. 00) withdraw(2. 00); // charge $2 fee } } • didn't need to say super. get. Balance() because the Fee. Account subclass doesn't override that method (it is unambiguous which version of the method we are talking about) 25

super and constructors • if the superclass has a constructor that requires any arguments

super and constructors • if the superclass has a constructor that requires any arguments (not ()), you must put a constructor in the subclass and have it call the super-constructor (call to super-constructor must be the first statement) public class Point 2 D { private int x, y; public Point 2 D(int x, int y) { this. x = x; this. y = y; } } public class Point 3 D extends Point 2 D { private int z; public Point 3 D(int x, int y, int z) { super(x, y); // calls Point 2 D constructor this. z = z; } } 26

The instanceof keyword • Performs run-time type check on the object referred to by

The instanceof keyword • Performs run-time type check on the object referred to by a reference variable • Usage: object-reference instanceof type (result is a boolean expression) • if type is a class, evaluates to true if the variable refers to an object of type or any subclass of it. • if type is an interface, evaluates to true if the variable refers to an object that implements that interface. • if object-reference is null, the result is false. • Example: Object o = my. List. get(2); if (o instanceof Bank. Account) ((Bank. Account)o). deposit(10. 0); 27

Some instanceof problems Object o = new Bank. Account(. . . ); Bank. Account

Some instanceof problems Object o = new Bank. Account(. . . ); Bank. Account c = new Checking. Account(. . . ); Bank. Account n = new Numbered. Account(. . . ); Checking. Account c 2 = null; T/F ? ? ? o instanceof Object _______ o instanceof Bank. Account _______ o instanceof Checking. Account _______ c instanceof Bank. Account _______ c instanceof Checking. Account _______ n instanceof Comparable _______ n instanceof Numbered. Account _______ c 2 instanceof Object _______ 28

Which method gets called? Bank. Account b = new Fee. Account("Ed", 9. 00); b.

Which method gets called? Bank. Account b = new Fee. Account("Ed", 9. 00); b. withdraw(5. 00); System. out. println(b. get. Balance()); • Will it call the withdraw method in Bank. Account, leaving Ed with $4? • Will it call the withdraw method in Fee. Account, leaving Ed with $2 (after his $2 fee)? 29

A hint about the right behavior Array. List list = new Array. List(); list.

A hint about the right behavior Array. List list = new Array. List(); list. add(new Bank. Account("Ed", $9. 0)); for (int i = 0; i < list. size(); i++) { Object o = list. get(i); System. out. println(o); } • Does it print "[email protected] 87 C" or "Ed $9. 00"? 30

The answer: dynamic binding • The version of withdraw from Fee. Account will be

The answer: dynamic binding • The version of withdraw from Fee. Account will be called • The version of an object's method that gets executed is always determined by that object's type, not by the type of the variable • The variable should only be looked at to determine whether the code would compile; after that, all behavior is determined by the object itself 31

Static and Dynamic Binding • static binding: methods and types that are hard-wired at

Static and Dynamic Binding • static binding: methods and types that are hard-wired at compile time • static methods • referring to instance variables • the types of the reference variables you declare • dynamic binding: methods and types that are determined and checked as the program is running • non-static (a. k. a virtual) methods that are called • types of objects that your variables refer to 32

Polymorphism • inheritance, like interfaces, provides a way to achieve polymorphism in Java •

Polymorphism • inheritance, like interfaces, provides a way to achieve polymorphism in Java • polymorphism: the ability to use identical syntax on different data types, causing possibly different underlying behavior to execute • example: If we have a variable of type Bank. Account and call withdraw on it, it might execute the version that charges a fee, or the version from the checking account that tallies interest, or the regular version, depending on the type of the actual object. 33

Type-casting and objects • You cannot call a method on a reference unless the

Type-casting and objects • You cannot call a method on a reference unless the reference's type has that method Object o = new Bank. Account("Ed", 9. 00); o. withdraw(5. 00); // doesn't compile • You can cast a reference to any subtype of its current type, and this will compile successfully ((Bank. Account)o). withdraw(5. 00); 34

Down-casting and runtime • It is illegal to cast a reference variable into an

Down-casting and runtime • It is illegal to cast a reference variable into an unrelated type (example: casting a String variable into a Bank. Account) • It is legal to cast a reference to the wrong subtype; this will compile but crash when the program runs • Will crash even if the type you cast it to has the method in question ((String)o). to. Upper. Case(); crashes ((Fee. Account)o). withdraw(5. 00); crashes // // 35

Summary of Polymorphism Object instantiated as: Can/Cannot be cast: Child or Later Descendent Class

Summary of Polymorphism Object instantiated as: Can/Cannot be cast: Child or Later Descendent Class To Parent or Earlier Ancestor (and back to its original class) Parent or Earlier Ancestor Class To Child or Later Descendent To any Interface it implements (and back to its original class) Implementing Class To any “incompatible class” Any Abstract Class or Interface cannot be instantiated 36

A dynamic binding problem class A { public void method 1() { System. out.

A dynamic binding problem class A { public void method 1() { System. out. println( “A 1”); } public void method 3() { System. out. println( “A 3”); } } class B extends A { public void method 2() { System. out. println( “B 2”); } public void method 3() { System. out. println( “B 3”); } } A var 1 = new B(); Object var 2 = new A(); var 1. method 1(); var 1. method 2(); var 2. method 1(); OUTPUT? ? ? ((A)var 2). method 3(); 37

A problem with interfaces public interface Shape 2 D { int get. X(); int

A problem with interfaces public interface Shape 2 D { int get. X(); int get. Y(); double get. Area(); double get. Perimeter(); } • Every shape will implement get. X and get. Y the same, but each shape probably implements get. Area and get. Perimeter differently 38

A bad solution public class Shape implements Shape 2 D { private int my.

A bad solution public class Shape implements Shape 2 D { private int my. X, my. Y; public Shape(int x, my. X = x; my. Y = } public int get. X() { public int get. Y() { int y) { y; return my. X; } return my. Y; } // subclasses should override these, please public double get. Area() { return 0; } public double get. Perimeter() { return 0; } } • BAD: the Shape class can be instantiated • BAD: a subclass might forget to override the methods 39

Abstract classes • abstract class: a hybrid between an interface and a class •

Abstract classes • abstract class: a hybrid between an interface and a class • used to define a generic parent type that can contain method declarations (like an interface) and/or method bodies (like a class) • like interfaces, abstract classes that cannot be instantiated (cannot use new to create any objects of their type) What goes in an abstract class? • implement common state and behavior that will be inherited by subclasses (parent class role) • declare generic behaviors that subclasses must implement (interface role) 40

Abstract class syntax • put abstract keyword on class header and on any generic

Abstract class syntax • put abstract keyword on class header and on any generic (abstract) methods • A class can be declared abstract even though it has no abstract methods • Any class with abstract methods must be declared abstract, or it will not compile • Variables of abstract types may be declared, but objects of abstract types cannot be constructed 41

Abstract class example public abstract class Shape implements Shape 2 D { private int

Abstract class example public abstract class Shape implements Shape 2 D { private int my. X, my. Y; public Shape(int x, my. X = x; my. Y = } public int get. X() { public int get. Y() { int y) { y; return my. X; } return my. Y; } public abstract double get. Area(); public abstract double get. Perimeter(); } Shape class cannot be instantiated • all classes that extend Shape must implement get. Area and get. Perimeter or else must also be declared abstract • 42

Extending an abstract class public class Rectangle extends Shape { private int my. Width,

Extending an abstract class public class Rectangle extends Shape { private int my. Width, my. Height; public Rectangle(int x, int y, int w, int h) { super(x, y); my. Width = w; my. Height = h; } public double get. Area() { return my. Width * my. Height; } public double get. Perimeter() { return 2*my. Width + 2*my. Height; } } //. . . example usage. . . Shape rect = new Rectangle(1, 2, 10, 5); 43

Interface / abstract class chart 44

Interface / abstract class chart 44

Questions, Practice problem • What are the differences between interfaces and abstract classes? Why

Questions, Practice problem • What are the differences between interfaces and abstract classes? Why is it useful that both exist in the Java language? When should one use an abstract class and when an interface? • Modify our old Int. Array. List and Int. Linked. List so that they have a common abstract base class Abstract. Int. List that contains the common functionality between them. 45