Chapter 7 Inheritance

Download Report

Transcript Chapter 7 Inheritance

Chapter 7 Inheritance
• Ada’s package construct
– Encapsulation of private data object
• Data type declared in package specification to allow compiler
to allocate storage in calling procedure instead of using ptr to
package
– Package creator can always declare data type in package spec as
ptr to data object in package body
– Operations on generalized data with
• Unconstrained arrays
• Discriminant field of record
• Generics
Inheritance syntax
• Scope rules allow names to be inherited in
enclosed block unless that block declares same
name
• Single inheritance
// Java syntax
public class Apple extends Java.applet.Applet
// C++; above with Apple: C.applet.Applet
-- Ada syntax
type apple is tagged private;
type newapple is new apple with record
extrafield: field_type
end record;
Inheritance implementation
• Compiler translates as before but
– Does not allow users to access private data
– Must include code for initialization (if there is a
constructor) with each storage allocation
• Storage allocated for derived type is typically
template for parent type plus additional fields for
new object (copy-based approach)
• Multiple inheritance (Smalltalk, C++, sort of Java)
– Object inherits properties of all “parents” – overlap
issues
Inheritance implementation of
methods
• Data object inherits methods that are valid for its
parents (key word: protected)
• Can redefine implementation of method
– Local name always makes non-local name invisible
• Parent method can be defined as virtual
– Binding to virtual method is determined at execution
time
– Table maintained of class; storage and methods – ptr to
method of current object
Abstract classes
• Parent class does not allow objects of that
type to be created
– Ex: stack type with each derived type
specifying the type of stack
• In C++ , objects cannot be created with
classes that have null virtual functionsprogrammer must derive a class and define
the function
Polymorphism
• I don’t agree with the text’s claim that overloading
of operators at compile time is a limited form of
polymorphism
– Ada’s generic packages/functions allow functions to be
instantiated for any type that satisfies generic definition
(range, digits for numeric, private for most others) –
compiler provides a copy of the code for each type,
with appropriate amount of storage allocated
• Dynamic polymorphism is the dynamic binding of
implementation (and type) to virtual function