[5-1]Programming in Java
Inheritance and
Polymorphism
Lecture5
[5-2]Programming in Java
Objectives
• Inheritance
Inheritance(super/sub-class)
Overriding, Field Hiding and Super
Final Classes and Methods(security, optimization)
Cast and Instanceof
Abstract Methods and Classes
• Polymorphism
• Design(Isa/HasA)
[5-3]Programming in Java
• Inheritance: Reuse of proven and debugged software• Polymorphism: handle existing and yet-to-be-specified, and add new capabilities
• Relationships among Classes
– ISA: sub/super-class– HASA: composition, an object has one or more objects of other classes as members – Coordination: operations by public fields & methods
Key Concepts
[5-4]Programming in Java
• Subclass/Superclass• Direct superclass / indirect superclass • Single Inheritance/multiple inheritance• Inheritance Hierarchy(tree-like/network-like)
• Inheritance and Interfaces in Java • Inheritance: class subclass extends superclass• Object: all classes are subclass of Object(root) • Interfaces: achieve many of the advantages of multiple inheritance
• Relationship between Superclass and Subclass Objects• Subclass-object-is-a-superclass-object• A superclass object is not a subclass object• Use an explicit cast to convert a superclass reference to a subclass reference(Just as type coercion)
Inheritance
[5-13]Programming in Java
• Field Hiding What is Field Hiding?
—A field with the same name as a superclass’s filed is declared in subclass
Notes
—The hidden field in the superclass still exists
—The hidden field may be accessed by super, or referencing a superclass’s object
—When a field of an object is accessed, the declared type of the object determine either super- or sub-class’s field will be used
Field
• Field Inheritance: magCard
[5-14]Programming in Java
Example
Public class TestHiddenField
{ public static void main(String args[ ] )
{ D200_Card my200 = new D200_Card();
my200.balance = 50.0;
System.out.println(“Supper:”+my200.getBalance());
if (my200.performDial())
System.out.println(“Subclass:”+my200.balance);
}
}
0.0
49.5
[5-15]Programming in Java
• Overriding
— Replace a superclass’s method implementation by a new one in the subclass
—Requirements• The old method and the new method must h
ave the same signature and return type. (if different, such a redefinition is not overriding, but is simply an example of overloading)
• The method must be non-static
Method
• Method Inheritance : IC-Card
[5-16]Programming in Java
• Super may be used to refer to the overridden method of the superclass
• The throws clauses may be different: the overriding method has fewer exception types(or no throws)
• The overriding method may have new modifiers,but must provide more access permissions. If protected in superclass, then protected or public, must not be private in subclass
• Dynamic Method Call: when a method of an object is called, the actual type of the object determine which implementation will be used
Notes
[5-17]Programming in Java
class SuperShow {
public String str = “SuperStr”;
public void show() {
System.out.println(“Super.show:” + str); }
}
class ExtendShow extends SuperShow {
public String str = “ExtendStr”;
public void show() {
System.out.println(“Extend.show” + str); }
public static void main(String[] args) {
ExtendShow ext = new ExtendShow();
SuperShow sup = ext;
Example(1)
[5-18]Programming in Java
sup.show();//show of actual type, i.e. ExtendShow
ext.show();
System.out.println(“sup.str=”+sup.str);
System.out.println(“ext.str =”+ext.str);
}
}
• Two kinds of reference: actual type(ext), super type(sup)
• Result: Extend.show:ExtendStr // actual type: Extend
Extend.show:ExtendStr
sup.str = SuperStr // declared type: SuperShow
ext.str = ExtendStr // declared type: ExtendShow
Example(2)
返回
[5-19]Programming in Java
• Function
Reference the current object as an instance of the superclass, when access fields and methods
Supper
• Use
Super.variable
Super.Method([paramlist])
Super([paramlist])
Note:super.method always call the superclass’s(overridden) method, not the subclass’s(overriding) method.
[5-20]Programming in Java
SubClass Instance in Memory(1)public clas SupClass {
private int supPriMember; protected int supPtroMember; public int supPubMember; public static int supStaMember; public void memothd(int x, double y) {System.out.pintln(“SuperClass.method”);}}
public clas SubClass extends SupClass{
private int subPriMember; protected int subPtroMember; public int subPubMember; public static int subStaMember; public void memothd(int x, double y) {System.out.pintln(“SubClass.method”);}}
public clas SubSubClass extends SubClass{
private int subSubPriMember; protected int subSubPtroMember; public int subSubPubMember; public static int subSubStaMember}};
SuperClass obj1 = new SuperClass();
SubClass obj2 = new SubClass();
SubSubClass obj3 = new SubSubClass();
[5-21]Programming in Java
SubClass Instance in Memory(2)
对象 Obj1supPriMember
supProMember
supPubMember
对象 Obj2supPriMember
supProMember
supPubMember
subPriMember
subProMember
subPubMember
子对象
对象 Obj3
supPriMember
supProMember
supPubMember
subPriMember
subProMember
subPubMember
subPriMember
subProMember
subPubMember
子对象
[5-22]Programming in Java
• Select and Invoke a Superclass’s Constructor• Explicit call
super() is the first statement of new constructor
Constructors in Subclasses
• Automatic call
If super() is not the first statement, call the no-ar
g constructor of the superclass. If there is no such
constructor, an explicit call of superclass’s constr
uctor with parameters must be called
[5-23]Programming in Java
class Attr {
private String name;
private Object value = null;
public Attr(String nameOf) { name = nameOf; }
public Attr(String nameOf,Object valueOf) {
name = nameOf; value = valueOf; }
public String nameOf() { return name; }
public Object valueOf() { return value; }
public String valueOf(Object newValue) { Object oldVal = value;
value = newValue; return oldVal; }
}
Example(1)
[5-24]Programming in Java
Example(2)
class ColorAttr extends Attr {private ScreenColor myColor; // the decoded color
public ColorAttr(String name, Object value) { super(name,value); decodeColor(); } public ColorAttr(String name) { this(name,”transparent”); } public ColorAttr(String name,ScreenColor value) { super(name,value.toString()); myColor = value; } public Object valueOf(Object newValue) { //do the superclass’s valueOf work first
Object retval = super.valueOf(newValue); decodeColor(); return retval; } /** Set value to ScreenColor , not description*/
[5-25]Programming in Java
Notes on Constructors
• “this()” can call a constructor in the class itself
• Subclass need not to have the same constructor signatures as superclass
• Default constructor of subclass starts by calling the no-arg constructor of the superclass
• If the superclass has not any non-arg constructors, subclass must provide at least one constructor
• If a superclass’s constructor calls a method, the method would be mostly overridden in subclass
[5-26]Programming in Java
• Initialize by default (0,\u0000,false,null), and call t
he subclass’s constructor(i.e. the following 3 steps)
• Call the superclass’s constructor
• Initialize by declaration assignment
• Execute the subclass’s constructor body
Initializing Orders in Subclass
[5-27]Programming in Java
class X {
protected int xMask= 0x00ff;
protected int fullMask;
public X() {
fullMask = xMask; }
public int mask(int orig) {
return (orig & fullMask);
}
}
class Y extends X {
protected int yMask= 0xff00;
public Y() {
fullMask |= yMask;
}
}
? How is a Y object to be created?
Example(1)
[5-28]Programming in Java
Step Action xMask yMask fullMask
0 Default 0 0 0
1 Call Y constructor 0 0 0
2 Call X constructor 0 0 0
3 Initialize X fields 0x00ff 0 0
4 Execute X Constructor 0x00ff 0 0x00ff
5 Initialize Y fields 0x00ff 0xff00 0x00ff
6 Execute Y constructor 0x00ff 0xff00 0xffff
Example(2)
[5-29]Programming in Java
class X {
protected int xMask= 0x00ff;
protected int fullMask;
public X() {
fullMask = mask(xMask);
}
public int mask(int orig) {
return (orig & fullMask);
}
}
class Y extends X {
protected int yMask= 0xff00;
public Y() {
fullMask |= yMask;
}
}
Example(3)
[5-30]Programming in Java
Step Action xMask yMask fullMask
0 Default 0 0 0
1 Call Y constructor 0 0 0
2 Call X constructor 0 0 0
3 Initialize X fields 0x00ff 0 0
4 Execute X Constructor 0x00ff 0 0
5 Initialize Y fields 0x00ff 0xff00 0
6 Execute Y constructor 0x00ff 0xff00 0xff00
Example(4)
[5-31]Programming in Java
class X {
protected int xMask= 0x00ff;
protected int fullMask;
public X() {
fullMask = mask(xMask);
}
public int mask(int orig) {
return (orig & fullMask);
}
}
class Y extends X {
protected int yMask= 0xff00;
public Y() {
fullMask |= yMask;
}
public int mask(int orig) {
return (orig | fullMask);
}
}
Example(5)
[5-32]Programming in Java
Step Action xMask yMask fullMask
0 Default 0 0 0
1 Call Y constructor 0 0 0
2 Call X constructor 0 0 0
3 Initialize X fields 0x00ff 0 0
4 Execute X Constructor 0x00ff 0 0x00ff
5 Initialize Y fields 0x00ff 0xff00 0x00ff
6 Execute Y constructor 0x00ff 0xff00 0xffff
Example(6)
[5-33]Programming in Java
• Final Methods
—Can not be re-implemented(overridden)
—The final version of the method
—Static and private methods are implicitly final
Final Method & Final Class
• Final Classes: Preventing Inheritance —Can not be extended(inherited)
—All Methods in a final class are implicitly final
[5-34]Programming in Java
• Security: ‘final’ improves the security
Behavior of final method is determined, unless it calls non-final methods
The associated fields of final method should be private, otherwise subclasses may change the method behavior through changing these fields
Final classes can not be extended(also a defect)
Use non-final class with methods all final, so that the class can be extended, but the method can not be re-implemented
Security
[5-35]Programming in Java
(1) Optimization: ‘Final’ simplifies the optimization
• Some public steps of method call are omitted, e.g. Match formal-actual para.;Push return addr. to stack
• Inline the code: Removing calls to final methods, and replacing them with the expanded code of their definitions at each method call location
(2) Efficiency
• ‘Final’ makes some types checked at compile time, types for non-final reference are checked at run time
• Dynamic binding (such as dynamically select a method implementation from several ones) has more overhead than static binding
Optimization and Efficiency
[5-36]Programming in Java
(1) Notation • <type> <var> = (<type>)<var>• Convert an object from one class to another• Just as type coercion (by means of casts)
(2) Casting Up(Widening)• To assign a subclass object to a superclass variable• Safe casting
(3) Casting Down(Narrowing) • To assign a superclass object to a subclass variable• Unsafe casting(not always valid)• If an object has been assigned to a reference of one of its superclasses, it’s acceptable to cast that object back to its own type• Employee:john; class Manager extends Employee,…
Manager boss = (Manager) john;
Cast
[5-38]Programming in Java
• The Operator
i instanceof C
i is an instance of class C
• Example
if ( john instanceof Manager) {
Manager boss = (Manager) john; }
• Note
null instanceof Type is false for any Type
The Instanceof Operator
[5-39]Programming in Java
• Casts can only be used within an inheritance hie
rarchy
• instanceof should be used to check hierarchy b
efore casting from a parent to a child, otherwise a c
lassCastException occurs
• Performing a cast is not usually a good idea, be
cause the dynamic binding often automatically loc
ates the correct method
Notes on Cast
[5-40]Programming in Java
• Abstract Method A method has not been specified(signature only) Abstract methods must be implemented in non-
abstract subclasses
Abstract Methods/Classes
• Abstract Class: one or more abstract methods Abstract classes may have concrete data and methods
• Notes
No instance of abstract superclasses can be instantiated
Superclass’s methods may be overridden by abstract methods(change concrete to abstract)
The abstract method gives the class designer considerable power over how subclasses will be implemented in a class hierarchy
• Example
[5-43]Programming in Java
• Methods
Polymorphism in compilation: static binding — Overloading(methods with different signatures)
Polymorphism in runtime: combination dynamic binding with inheritance – Overriding(inheritance with redefinition)
Variable:static type (compile time) /dynamic type(runtime)
Method:overload(compile time)/override(runtime)
Polymorphism
•Notes
Subclass-object-is-a-superclass-object, so an object can be referenced by the super types
A class’s constructor usually invokes a superclass’s constructor, because creating an object also leads to creating another object of the superclass
A variable of type Object may refer to any object
[5-44]Programming in Java
GraphicObject g = new Circle();
g.draw();
Casting Up
Circle.draw()
在 C++ 中 ,用虚函数实现动态绑定;
在 JAVA 中,缺省情况就是动态绑定;否则可用 final 定义
Example
[5-47]Programming in Java
• IsA and HasA
(1) Different Meanings
• Inheritance vs. Composition
• Example: Point, Pixel(ColorPoint), Circle
• The difference is subtle: handle with care
Class/Subclass Design
(2) Design Carefully
• IsA: Employee--Manager, Engineer, Clerk,…
IsA Fact: an engineer is an employee
IsA Problem: An engineer may be a manager as well
• HasA:
Role-Employee(contains several Role Objects)
HasA Fact: an employee may play several roles
[5-48]Programming in Java
class Employee {
String name;
String dept; …}
class Manager extends Employee {
int level;
String secretaryname;
Day workday; … }
class Engineer extends Employee {
String speciality;
Day workday; … }
class Role { String Rolename; Day workday; …}class Manager extends Role {
int level; String secretaryname; … }class Engineer extends Role {
String speciality; … }Class Employee { String name; String dept; Role business; Role posttitle;…}
Example
[5-49]Programming in Java
Assignment
• P454 : 9.11 、 9.15 、 9.26