Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... ·...
Transcript of Inheritance, polymorphism, interfacespeople.rennes.inria.fr/Delphine.Demange/ens/prog2/PROG2... ·...
Inheritance, polymorphism, interfaces
"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
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
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
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;
}}
• Now create a Wizard...
public class Wizard { // ugh, gotta copy and paste // Dude’s stuff }
Very basic inheritance
• Now create a Wizard...
But Wait! A Wizard does and has everything a
Dude does and has!
Very basic inheritance
• Now create a Wizard...
Don’t Act Now! You don’t have to Copy & Paste!
Very basic inheritance
Buy Inheritance!
public class Wizard extends Dude {
}
• Wizard is a subclass of Dude
• Dude is a super-class of Wizard
• Wizard inherits Dude
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
Buy Inheritance!• Now augment a Wizard
public class Wizard extends Dude {
String[] spells;
public class cast(String spell) {
// cool stuff here
...
points += 10;
}
}
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();
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
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()
What’s going on?
You can only inherit from one class
You can only inherit from one class
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!!
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
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(...)
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"?
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
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
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
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
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
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.
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
Abstract class
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)
Abstract method
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
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);
Generic methods
public <T> void inspect(T t) {
System.out.println("T: " + t.getClass().getName());
}
...
<String>inspect(String s);
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?
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
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
}
}
Implementing interfaces• Implementations provide complete methods:
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