View
216
Download
0
Embed Size (px)
Citation preview
1
Inheritance
Lesson #5
Note: CIS 601 notes were originally developed by H. Zhu for NJIT DL Program. The notes were subsequently revised by M. Deek.
2
Correction (to Point Class)
class Point { public:…
int getX() const {return x;};int getY(){return y;};
void setX(int valX) {x=valX;}; // set x…}
3
Correction
const Point P1(10, 20);//P43
Point P2(30, 50);
P1.getX();
P2.getX();//a const function can be //called by a non-const object!!!
P1.SetX(100); //error! P1 is a const obj
P2.SetX(100); //ok
4
An Example: FString #include <iostream.h> #include <iomanip.h> #include <string.h> class FString { public: FString(); FString( const char * s ); // Construct from a C-style string. FString( const FString & s ); // Construct from another FString. FString & Append( const FString & s ); // Append another FString to current object. FString & Assign( const char * s ); // Assign a C-style string to current object.
5
Fstring.h
FString & Assign( const FString & s ); // Assign an FString to current object. const char * CString() const; // Convert current object to a C-style string. int Compare( const FString & s ) const; // Implement the standard strcmp() function. // Case-sensitive. int IsLess( const FString & s ) const; // Return 1 if current object is less than s. int IsGreater( const FString & s ) const; // Return 1 if current object is greater than s.
6
FString
int IsEqual( const FString & s ) const; // Return 1 if current object is equal to s. FString & GetLine( istream & inp ); // Get a line of input from a stream. friend istream & operator >>( istream & inp, FString & s ); friend ostream & operator <<( ostream & inp, const FString & s ); enum { MaxSize = 256 }; // Maximum allowable string size private: char str[MaxSize+1]; // String characters };
7
Fstring.cpp #include "fstring.h" FString::FString() { str[0] = '\0'; } FString::FString( const char * S ) { strncpy( str, S, MaxSize ); str[MaxSize] = '\0'; } FString::FString( const FString & S ) { strcpy( str, S.CString() ); } FString & FString::Append( const FString & S ) { strncat( str, S.CString(), MaxSize ); return *this; }
8
Fstring.cpp FString & FString::Assign( const char * S ) { strncpy( str, S, MaxSize ); return *this; } FString & FString::Assign( const FString & S2 ) { strncpy( str, S2.str, MaxSize ); return *this; } const char * FString::CString() const { return str; } int FString::Compare( const FString & S2 ) const { return strcmp( str, S2.str ); }
9
Fstring.cpp int FString::IsLess( const FString & S2 ) const { if (strcmp( str, S2.str ) < 0) return 1; else return 0; } int FString::IsGreater( const FString & S2 ) const // Return 1 if current object is greater than s. { if (strcmp( str, S2.str ) > 0) return 1; else return 0; } int FString::IsEqual( const FString & S2 ) const // Return 1 if current object is equal to s. { if (strcmp( str, S2.str ) == 0) return 1; else return 0; }
10
Fstring.cpp FString & FString::GetLine( istream & inp ) { inp.getline( str, MaxSize+1 ); return *this; } istream & operator >>( istream & inp, FString & S ) { inp >> setw(S.MaxSize+1) >> S.str; return inp; } ostream & operator <<( ostream & os, const FString & S ) { os << S.str; return os; }
11
Fstrtst.cpp
#include "fstring.h" class Employee { public: Employee( const char *, const char * ); friend ostream & operator <<( ostream &, const
Employee & ); private: FString LastName; FString FirstName; };
12
Fstrtst.cpp
Employee::Employee( const char * lname, const char * fname )
:LastName(lname), FirstName(fname) { } ostream & operator <<( ostream & os, const
Employee & E ) { os << E.FirstName << ' ' << E.LastName; return os; }
13
Fstrtst.cpp int main() {FString name1; FString name2; name1.Assign( "Fred" ); name2.Assign( name1 ); name1.Assign( "Fred " ); name2.Assign( "Smith" ); name1.Append( name2 ); // "Fred Smith" int n = name1.Compare( name2 ); if( n < 0 ) cout << "The first name is less\n"; else if( n == 0 ) cout << "The names are equal\n"; else cout << "The second name is less\n"; if( name1.IsLess( name2 )) cout << "The first name is less\n";
14
Fstrtst.cpp cout << "Enter two names:\n"; name1.GetLine( cin ); name2.GetLine( cin ); n = name1.Compare( name2 ); if( n < 0 ) cout << "The first name is less\n"; else if( n == 0 ) cout << "The names are equal\n"; else cout << "The second name is less\n"; if( name1.IsLess( name2 )) cout << "The first name is less\n"; const char * vp = name1.CString(); cout << vp << endl; Employee E( "Johnson", "Harvey" ); cout << E << endl; return 0; }//cis601/cis601source/chap06/Fstring/fstrtst.dsw
15
16
17
Contents
1. Classification2. Sharing3. Inheritance4. Subclass5. The Categories of Inheritance6. Abstract Class
18
Classification An object can be of a certain class but not its
creator. An apple is of Fruit, but is not the instance of Fruit.
In this view, classes are like sets. John is a man. Mary is a woman. Spot is a dog. All men are people. All women are people. All people are mammals. All dogs are mammals.
19
Classification/Inheritance
Mammal
People
Bird
Dog
Animal
man woman
John Mary
. . . . .
Classification
Inheritance
20
Classification
Classification arises from the universal need to describe uniformities of collections of instances.
Classification is a basic idea for understanding the concept inheritance
21
Classification/Inheritance Commonality
The base class captures the common information (attributes) and features (operations) of the derived classes.
22
Classification/Inheritance Customization
An existing class is used to create a customized version of the class.
Common Design Interface A base class may define the design
requirements for its derived classes by specifying a set of member functions that are required to be provided by each of its derived classes.
23
Sharing Sharing is important in object-orientation. Inheritance is a technique that promotes
sharing. Inheritance means that new classes can
be derived from existing classes . A subclass inherits the attributes and the
operations of a superclass (base class) but a subclass (derived class) can define additional operations and attributes.
24
Sharing Sharing can be seen as a specialization
mechanism. Instances of a subclass are specializations
(additional state and behavior) of the instances of a superclass.
Sharing can also be seen as generalization mechanism. Instances of a superclass generalizes
(restricts) the instances of a subclasses.
25
Sharing
Sharing is also the basic idea of inheritance. The ability of one class to share the
behavior of another class without explicit redefinition.
An approach which allows classes to be created based on a old class.
26
Three dimensions of sharing
Static or dynamic sharing: At times, sharing patterns have to be fixed. This can be
done at object creation (static) or when an object receives a message (dynamic).
Implicit or explicit sharing: The programmer directs the patterns of sharing (explicit)
or the system does it automatically (implicit).
Per object or per group sharing: Behaviors can be specified for an entire group of objects
or can be attached to a single object.
27
Inheritance Purpose
1. Reusing existing design reduces software development and testing costs.
2. A new class inherits the data members and member functions of an existing class.
28
What is Inheritance?
1. Inheritance is a mechanism for expressing similarity.
2. Inheritance is a natural property of classification.
3. Inheritance is a mechanism that allows a class A to inherit properties of a class B.
29
What is Inheritance?
Assume ''A inherits from B''. Then, objects of class A have access to attributes and methods of class B without the need to redefine them.
30
Superclass/Subclass If class A inherits from class B, then B
is called superclass of A. A is called subclass of B. Objects of a subclass can be used where objects of the corresponding superclass are expected. This is due to the fact that objects of the subclass share the same behavior as objects of the superclass.
31
Person
Administrator Faculty Student
superclass
subclasses
Example:
32
Subclasses
Subclasses refer to not only inheritance of specifications but also to inheritance of implementation and so can be viewed as reusability mechanism.
33
Important aspects of subclasses
Modifiability The degree of modifiability determines
how attributes and methods inherited from a superclass can be modified in a subclass. In this context, an approach of distinguishing modifiability of the objects state (attributes) and the objects behavior (operations) are used.
34
Attributes
1. No redefinition: modification is not allowed.
2. Arbitrary redefinition: redefinition without constrained is allowed.
3. Constrained redefinition: the domain of attributes is constrained.
4. Hidden redefinition: definitions of attributes are hidden in subclass to avoid conflicts.
35
For operations
1. Arbitrary redefinition: all changes to operations are allowed.
2. Constrained redefinition: Parts of the signature of methods in
subclasses have to be subtypes of the parts of the methods of the superclass.
This is important in overriding and overloading of methods.
36
Naming conflicts
Conflicts between a superclass and a subclass. when attributes or methods defined in a
subclass have the same name as attributes or methods defined in the superclass.
This is resolved by overriding.
37
The categories of Inheritance
Whole/Partial Inheritance: Whole Inheritance is when a class inherits all
the properties and operations from its superclass.
Partial Inheritance is when only some properties are inherited while others are suppressed.
38
The Categories of Inheritance
Default inheritance: inherited properties and constraints can be modified.
Strict inheritance: doesn't allow the user to modify inherited properties or constraints.
39
The categories of Inheritance
Single (simple) inheritance: A class can inherit from only one
superclass. This means the inheritance hierarchy forms a tree.
Multiple inheritance: A class can have more than one
superclass.
40
What is Multiple Inheritance?
Multiple inheritance is when a class inherits from more than one class (e.g. A inherits from B1, B2, ..., Bn).
Naming conflicts can be introduced if at least two superclasses define properties with the same name.
41
Naming Conflicts
If attributes or methods defined in one superclass have the same name as attributes or methods defined in another superclass.
42
B1{//… int x;//…}
B2{//… int x; public: int getValue();}
B3{//… int x;public: int getValue();}
A{}
Multiple Inheritance and Naming conflicts
43
Conflict Resolution
1. Using the order of the superclass If there are more attributes or methods with
the same name in different superclasses, the ones occurring in the first class in the list of superclasses are inherited (done by the compiler).
If the order is from left to right, then x means x of B1, and getValue() means the getValue() of B2.
44
Conflict Resolution
2. Determined by the user The user can inherit conflicting
attributes or methods, but has to explicitly rename conflicting attributes or methods in the subclass (done by the user)
B1::x; or B2::x; B2::getValue(); or B3::getValue();
45
Precedence conflicts We have class A with attribute a, class B which
is a subclass of A and redefines attribute a, class C which is also a subclass of A, and class D which is a subclass of B and C (multiple inheritance).
Class D can inherit the redefined version of a from class B or the original version from class C.
Which version of attribute a should be inherited?
46
Precedence conflicts
class A{a;}
class B: public A{}
class C: public A{a;//redefined}
class C: public B, C{?}
47
Conflict Resolution
The same as with naming conflicts: Use the order of the superclass set by
the compiler. Use the explicit class name given by
the user.
48
Abstract class
A class without any instance. Mammal is an abstract class: only for
classification and inheritance. Never make objects of the class.
49
Abstract class
It is also possible to have a classification which does not any have code behind it: Resizable class is a class of objects that
may be resized.
50
What is Abstract Class
A class A is called abstract class if it is only used as a superclass for other classes. Class A only specifies properties. It is not used to create objects. Derived classes must define the properties of A.
51
Abstract Classabstract class DrawableObject { attributes: methods:
print() }
class Point inherits from DrawableObject { attributes:
int x, y;
methods: setX(int newX) ;getX();setY(int newY);getY();print(); /* Redefined for Point */
}
52
A Formula for Subclasses
Subclass ::=<Id, SupeId, Ds, Ops, Intfc>, where Id is the identification or name of the subclass; SuperId is the identification or name of its
superclassor a set of ids of its superclases. Ds is the new space description (template) for
memory of the subclass; Op is the new set of operations’
implementation of the subclass; Int is the new interface of the subclass.
53
Reuse
Many take inheritance as a reusing tool.
In this case, we can take inheritance as a code reusing tool.
For example: There are location class, point class and
a line class.
54
ReuseClass Loc{
int x, y;
public:
int getX();
int getY();
void setX(int);
void setY(int)
};
Class point inherited from Loc
{int color;
int getColor();
void setColor(int);}
Class line inherited from Point
{int endX, endY;
float weight;
float getWeight();
void setWeight(int);
}
55
Reuse Is that all right? Location, point and line belong to three
different categories of things. They should not be considered as
having superclass/subclass relation.
56
Inheritance and Classification
Classification implies inheritance (whole and simple inheritance).
Inheritance may effect clarity of classification (for multiple inheritance and for part inheritance)
57
Example
Is a class of ostrich a subclass of class bird? (an ostrich can not fly).
In terms of classification: No, if there is a Ds for “can fly”. Yes, if there was no Ds for “can fly”.
In terms of inheritance: Yes for both cases, because an ostrich
inherits partly from bird.
58
Two views for a plane class Head{dsh, oph}; class Body{dsb, opb}; class Wing{dsw, opw}; class Tail{dst, opt}; class Plane inherits
from Head, Body, Wing, Tail
{ dsp, opp};
class Head{dsh, oph};
class Body{dsb, opb};
class Wing{dsw, opw};
class Tail{dst, opt};
class Plane
{Head h;
Body b;
Wing w;
Tail t;
dsp;
opp;
};
59
Declaring Derived Classes
Class class_name: access_specifieropt or base_class {
Member_list
} access_specifier ::= public|protected|
private(default)
60
A simple Example #include <iostream.h> class Door { public: Door(); bool isOpen() const; void open(); void close(); protected: bool shut; };
61
Ex5door.cpp Door::Door() : shut(true) {}; bool Door:: isOpen() const { return !shut;}; void Door:: open() { shut= false;}; void Door:: close() { shut = true;};
62
Ex5door.cpp class LockableDoor : public Door { public: LockableDoor(); bool isLocked() const; void open(); void lock(); void unlock(); protected: bool locked; };
63
Ex5door.cpp LockableDoor::LockableDoor():Door(),
locked(true) {}; bool LockableDoor::isLocked() const { return locked;}; void LockableDoor::open() { if (!locked) Door::open();}; void LockableDoor::lock() { locked = true;}; void LockableDoor::unlock() { locked = false;};
64
Ex5door.cpp
main() { Door generic; LockableDoor bathDoor; generic.open(); bathDoor.lock(); bathDoor.open();
65
Ex5door.cpp if (!bathDoor.isOpen()) bathDoor.unlock(); if (generic.isOpen()) cout << "generic is open!"<< "\n"; else cout << "generic is closed!"<< "\n"; if (bathDoor.isOpen()) cout << "bathDoor is open!"<< "\n"; else cout << "bathDoor is closed!"<< "\n"; }
66
67
68
69
A complex Example
Test if the specified file exists If yes, find the lines containing “#include”
and output the lines. Else, do nothing.
70
Example ----The files
Testsrc.cpp (main())(File Structure) Fexcept.cpp File.cpp Srcfile.cpp Txtfile.cpp
Fexcept.h
File.h
Srcfile.h
Txtfile.h
71
Example The class structure
File
Text_File
Source_File
File_Exception
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
Readings
Readings Chapter 6 Sections 6.1.1 - 6.1.2