Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... ·...

39
Inheritance, polymorphism, interfaces

Transcript of Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... ·...

Page 1: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Inheritance, polymorphism, interfaces

Page 2: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

"is-a" relationship

• Similar things (sharing same set of attributes / operations): a group / concept

• Similar groups (sharing a subset of attributes / operations): a bigger group / a more general concept

• A student is a person

• An employee is a person

• A manager is an employee

• An object of the subgroup "is-a" object of the supergroup

Page 3: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Inheritance• Based on "is-a" relationship

• Subclass: more specialized; Superclass: more general

• Subclass is derived or inherits from superclass hence, the terms 'derived class' and 'base class'

• Objects of a subclass can be treated as objects of its superclass

• Objects in the same class have the same set of attributes (different values though) and operations

• Objects of subclass have all members of the superclass plus some more

Page 4: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

java.lang.Object

• The root of the class hierarchy.

• Every class has Object as a superclass.

• Provides a number of methods that are common to all objects (including arrays):

• clone()

• equals(Object o)

• hashCode()

• finalize()

• toString()

• + synchronization methods

Page 5: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Very basic inheritance

• Making a Game

public class Dude {public String name;public int points = 100

public void sayName() {System.out.println(name);

}

public void punchFace(Dude target) {target.points -= 10;

}}

Page 6: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

• Now create a Wizard...

public class Wizard { // ugh, gotta copy and paste // Dude’s stuff }

Very basic inheritance

Page 7: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

• Now create a Wizard...

But Wait! A Wizard does and has everything a

Dude does and has!

Very basic inheritance

Page 8: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

• Now create a Wizard...

Don’t Act Now! You don’t have to Copy & Paste!

Very basic inheritance

Page 9: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Buy Inheritance!

public class Wizard extends Dude {

}

• Wizard is a subclass of Dude

• Dude is a super-class of Wizard

• Wizard inherits Dude

Page 10: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Buy Inheritance!

• Wizard can use everything* the Dude has!

wizard1.points += 1;

• Wizard can do everything* Dude can do!

wizard1.punchFace(dude1);

• You can use a Wizard like a Dude too!

dude1.punchface(wizard1); *except for private fields and methods

Page 11: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Buy Inheritance!• Now augment a Wizard

public class Wizard extends Dude {

String[] spells;

public class cast(String spell) {

// cool stuff here

...

points += 10;

}

}

Page 12: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Inheriting from inherited classes

• What about a Grand Wizard?

public class GrandWizard extends Wizard {

public void sayName() {

System.out.println(“Grand wizard” + name)

}

}

grandWizard1.name = “Flash”

grandWizard1.sayName();

((Dude)grandWizard1).sayName();

Page 13: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

How does Java do that?• What Java does when it sees

grandWizard1.punchFace(dude1)

1. Look for punchFace()in the GrandWizard class

2. It’s not there! Does GrandWizard have a parent?

3. Look for punchFace()in Wizard class

4. It’s not there! Does Wizard have a parent?

5. Look for punchFace()in Dude class

6. Found it! Call punchFace()

7. Decrease points from dude1

Page 14: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

How does Java do that?

• What Java does when it sees ((Dude)grandWizard1).sayName()

1. Cast to Dude tells Java to start looking in Dude

2. Look for sayName()in Dude class

3. Found it! Call sayName()

Page 15: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

What’s going on?

Page 16: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

You can only inherit from one class

Page 17: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

You can only inherit from one class

Page 18: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

You can only inherit from one class

• What if Thief and Elf both implement

public void sneakUp()

• If they implemented differently, which sneakUp()does BadElf call?

Java Doesn’t Know!!

Page 19: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Chaining constructors• Recall that when a class defines no constructor, the

compiler will automatically add one. That is:class MaClasse { MaClasse() { super(); } ... }

• super() - call the constructor of the superclass

• All constructors (except those of java.lang.Object) call another constructor:

• a constructor of the superclass: super(...)

• another constructor of the same class: this(...)

• super() or this() are called on the first line of the new constructor

Page 20: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Virtual methods• A subclass can redefine methods inherited from its superclass.

• to specialize these methods to suit the new problem

• New and old version must have the same prototype:

• same return type

• same argument types

• Private, final methods cannot be overriden

• Private members are hidden from subclass

• Objects of the subclass will work with the new version of the methods

• Superclass’s methods of the same name can be reused by using the keyword super.methodName(...)

Page 21: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Polymorphism

• "exist in many forms"

• Object polymorphism: an object can be treated in different ways

• A Manager object can be seen as an Employee object as well

• Different objects interpret the same message differently: how do cats and dogs "talk"?

Page 22: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Upcasting• Cast "up" the inheritance diagram

• Take an object reference and treat it as if it refers to its base type

Cat c = new Cat("Tom"); Animal a = c; // upcasting

• Cannot invoke methods not provided by the base type

a.chaseTail(); //Error! method not found in class Animal

• But

a.makeASound(); //"Meow…", Cat's makeASound() gets to run

• java.lang.ClassCastException

Page 23: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Upcasting• Cast "up" the inheritance diagram

• Take an object reference and treat it as if it refers to its base type

Cat c = new Cat("Tom"); Animal a = c; // upcasting

• Cannot invoke methods not provided by the base type

a.chaseTail(); //Error! method not found in class Animal

• But

a.makeASound(); //"Meow…", Cat's makeASound() gets to run

• java.lang.ClassCastException

Page 24: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Upcasting• Cast "up" the inheritance diagram

• Take an object reference and treat it as if it refers to its base type

Cat c = new Cat("Tom"); Animal a = c; // upcasting

• Cannot invoke methods not provided by the base type

a.chaseTail(); //Error! method not found in class Animal

• But

a.makeASound(); //"Meow…", Cat's makeASound() gets to run

• java.lang.ClassCastException

Page 25: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Downcasting

• Cast "down" the inheritance diagram

Animal animal = new Cat("Tom"); //upcast ... Cat c = (Cat) animal; // downcast c.sayHello(); // "Meow.."

• But, not always possible. Why?

Animal animal = new Animal("Dummy"); ... Cat c = (Cat) animal; // run-time error

Page 26: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

PolymorphismAnimal pet1 = new Cat("tom"); Animal pet2 = new Cow("mini"); ... pet1.makeASound(); pet2.makeASound();

• The same message is interpreted differently depending on the object's type:

Dynamic binding

Page 27: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Dynamic binding• Method binding: connect a method call to a method

body

• Static/early binding: performed by compiler/linker before the program is run.

• the only option of procedural languages.

• Dynamic/late binding: performed at run-time

• Java uses late binding, except for static, final, and private methods.

• private methods are implicitly final.

Page 28: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Abstract class

• Sometimes we don't want objects of a base class to be created

• Examples:

• Animal, Cat, Cow, Dog,…

• An Animal object makes no sense

• What sort of sound does it make?

• Shape, Point, Rectangle, Triangle, Circle

• What does a generic Shape look like?

• How to draw it?

• Solution: make it an abstract class

Page 29: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Abstract class

Page 30: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Abstract method• Sometimes we want a method in base class to serve as the common

interface of subclasses' versions only:

• i.e. it should never be called

Animal.makeASound(). It contains only dummy code

• Solution: make it an abstract method

• An abstract method has only a declaration and no method body (i.e. no definition):

abstract void f();

• The class containing an abstract method MUST be qualified as abstract

• An abstract method must be overriden and defined in a derived class so that objects of that class can be created (concrete class)

Page 31: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Abstract method

Page 32: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Generic programming

• Write code that can be reused for objects of many different types

• Indicate some type parameters instead of actual types

• Java 1.5: generic classes and methods

Page 33: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Generic classes• General form of a generic class:

class A<T1, T2, ...> {...}

T1, T2, ... genericity parameters

• Example: class Stack<T>{ //generic stack

private int s;private Object[] P = new Object[100];public Stack() {s=-1;}public void push(T e) {s++; P[s]=e};...

}

Student tot = new Student("toto",...);Stack<Student> sStu = new Stack<Student>();sStu.push(toto);

Page 34: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Generic methods

public <T> void inspect(T t) {

System.out.println("T: " + t.getClass().getName());

}

...

<String>inspect(String s);

Page 35: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Interfaces

• Manipulate objects, without knowing how they work

• Useful when you have similar but not identical objects

• Useful when you want to use code written by others

• Java does not support multiple inheritance

• What if we want an object to be multiple things?

Page 36: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Interfaces• Define a “contract” that some classes will respect:

• Set of classes that share methods

• Declare an interface with the common methods

• Can use the interface, without knowing an object’s specific type

• A special type of class which:

• Defines a set of method prototypes

• Does not provide the implementation for the prototypes, only the definition (signature)

• Can also define final constants

• A class can implement any number of interfaces

Page 37: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Interface example public interface Comparable<T>{

public int compareTo(T o);

}

public class Name implements Comparable<Name>{

...

public int compareTo(Name n){

... //implementation of compareTo

}

}

Page 38: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Implementing interfaces• Implementations provide complete methods:

Page 39: Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... · 2016-12-12 · Inheritance • Based on "is-a" relationship • Subclass: more specialized;

Using interfaces

• All methods must be implemented

• All fields are final (cannot be changed)

• An interface name can be used as a class name:

I i; //I interface

• If an class A implements an interface I, the subclasses of A automatically implement I also