Title: Inheritance
1Inheritance
Note CIS 601 notes were originally developed by
H. Zhu for NJIT DL Program. The notes were
subsequently revised by M. Deek.
2Correction (to Point Class)
- class Point
- public
-
- int getX() const return x
- int getY()return y
- void setX(int valX) xvalX // set x
-
3Correction
- 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
4An Example FString
- include ltiostream.hgt
- include ltiomanip.hgt
- include ltstring.hgt
- 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.
5Fstring.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.
6FString
- 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 gtgt( istream inp,
- FString s )
- friend ostream operator ltlt( ostream inp,
- const FString s )
- enum MaxSize 256 // Maximum allowable
string size - private
- char strMaxSize1 // String characters
7Fstring.cpp
- include "fstring.h"
- FStringFString()
- str0 '\0'
-
- FStringFString( const char S )
- strncpy( str, S, MaxSize )
- strMaxSize '\0'
-
- FStringFString( const FString S )
- strcpy( str, S.CString() )
-
- FString FStringAppend( const FString S )
- strncat( str, S.CString(), MaxSize )
- return this
8Fstring.cpp
- FString FStringAssign( const char S )
- strncpy( str, S, MaxSize )
- return this
-
- FString FStringAssign( const FString S2 )
- strncpy( str, S2.str, MaxSize )
- return this
-
- const char FStringCString() const
- return str
-
- int FStringCompare( const FString S2 ) const
- return strcmp( str, S2.str )
9Fstring.cpp
- int FStringIsLess( const FString S2 ) const
- if (strcmp( str, S2.str ) lt 0) return 1
- else return 0
-
- int FStringIsGreater( const FString S2 )
const - // Return 1 if current object is greater than
s. - if (strcmp( str, S2.str ) gt 0) return 1
- else return 0
-
- int FStringIsEqual( const FString S2 ) const
- // Return 1 if current object is equal to s.
- if (strcmp( str, S2.str ) 0) return 1
- else return 0
10Fstring.cpp
- FString FStringGetLine( istream inp )
- inp.getline( str, MaxSize1 )
- return this
-
- istream operator gtgt( istream inp, FString S
) - inp gtgt setw(S.MaxSize1) gtgt S.str
- return inp
-
- ostream operator ltlt( ostream os, const
FString S ) -
- os ltlt S.str
- return os
11Fstrtst.cpp
- include "fstring.h"
- class Employee
-
- public
- Employee( const char , const char )
- friend ostream operator ltlt( ostream , const
Employee ) - private
- FString LastName
- FString FirstName
12Fstrtst.cpp
- EmployeeEmployee( const char lname, const
char fname ) - LastName(lname), FirstName(fname)
-
- ostream operator ltlt( ostream os, const
Employee E ) -
- os ltlt E.FirstName ltlt ' ' ltlt E.LastName
- return os
13Fstrtst.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 lt 0 )
- cout ltlt "The first name is less\n"
- else if( n 0 )
- cout ltlt "The names are equal\n"
- else
- cout ltlt "The second name is less\n"
- if( name1.IsLess( name2 ))
- cout ltlt "The first name is less\n"
14Fstrtst.cpp
- cout ltlt "Enter two names\n"
- name1.GetLine( cin )
- name2.GetLine( cin )
- n name1.Compare( name2 )
- if( n lt 0 )
- cout ltlt "The first name is less\n"
- else if( n 0 )
- cout ltlt "The names are equal\n"
- else
- cout ltlt "The second name is less\n"
- if( name1.IsLess( name2 ))
- cout ltlt "The first name is less\n"
- const char vp name1.CString()
- cout ltlt vp ltlt endl
- Employee E( "Johnson", "Harvey" )
- cout ltlt E ltlt endl
- return 0
- //cis601/cis601source/chap06/Fstring/fstrtst.dsw
15(No Transcript)
16(No Transcript)
17Contents
- Classification
- Sharing
- Inheritance
- Subclass
- The Categories of Inheritance
- Abstract Class
18Classification
- 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.
19Classification/Inheritance
Animal
Classification
Mammal
Bird
People
. . . . .
Dog
man
woman
Inheritance
John
Mary
20Classification
- Classification arises from the universal need to
describe uniformities of collections of
instances. - Classification is a basic idea for understanding
the concept inheritance
21Classification/Inheritance
- Commonality
- The base class captures the common information
(attributes) and features (operations) of the
derived classes.
22Classification/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.
23Sharing
- 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.
24Sharing
- 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.
25Sharing
- 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.
26Three 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.
27Inheritance
- Purpose
- Reusing existing design reduces software
development and testing costs. - A new class inherits the data members and member
functions of an existing class.
28What is Inheritance?
- Inheritance is a mechanism for expressing
similarity. - Inheritance is a natural property of
classification. - Inheritance is a mechanism that allows a class A
to inherit properties of a class B.
29What 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.
30Superclass/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.
31Example
Person
superclass
subclasses
Faculty
Student
Administrator
32Subclasses
- Subclasses refer to not only inheritance of
specifications but also to inheritance of
implementation and so can be viewed as
reusability mechanism.
33Important 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.
34Attributes
- No redefinition modification is not allowed.
- Arbitrary redefinition redefinition without
constrained is allowed. - Constrained redefinition the domain of
attributes is constrained. - Hidden redefinition definitions of attributes
are hidden in subclass to avoid conflicts.
35For operations
- Arbitrary redefinition
- all changes to operations are allowed.
- 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.
36Naming 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.
37The 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.
38The 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.
39The 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.
40What 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.
41Naming Conflicts
- If attributes or methods defined in one
superclass have the same name as attributes or
methods defined in another superclass.
42Multiple Inheritance and Naming conflicts
B2 // int x public int getValue()
B3 // int x public int getValue()
B1 // int x //
A
43Conflict Resolution
- 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.
44Conflict 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) - B1x or B2x
- B2getValue() or B3getValue()
45Precedence 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?
46Precedence conflicts
class A a
class B public A
class C public A a//redefined
class C public B, C ?
47Conflict 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.
48Abstract class
- A class without any instance.
- Mammal is an abstract class only for
classification and inheritance. Never make
objects of the class.
49Abstract 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.
50What 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.
51Abstract Class
- abstract 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 /
-
52A Formula for Subclasses
- Subclass ltId, SupeId, Ds, Ops, Intfcgt, 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.
53Reuse
- 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.
54Reuse
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)
- Class Loc
- int x, y
- public
- int getX()
- int getY()
- void setX(int)
- void setY(int)
55Reuse
- 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.
56Inheritance and Classification
- Classification implies inheritance (whole and
simple inheritance). - Inheritance may effect clarity of classification
(for multiple inheritance and for part
inheritance)
57Example
- 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.
58Two views for a plane
class Headdsh, oph class Bodydsb, opb
class Wingdsw, opw class Taildst, opt
class Plane Head h Body b Wing w Tail
t dsp opp
- class Headdsh, oph
- class Bodydsb, opb
- class Wingdsw, opw
- class Taildst, opt
- class Plane inherits from Head, Body, Wing, Tail
- dsp, opp
59Declaring Derived Classes
- Class class_name access_specifieropt or
base_class - Member_list
-
- access_specifier publicprotectedprivate(defa
ult)
60A simple Example
- include ltiostream.hgt
- class Door
- public
- Door()
- bool isOpen() const
- void open()
- void close()
- protected
- bool shut
61Ex5door.cpp
- DoorDoor() shut(true)
-
- bool Door isOpen() const
- return !shut
- void Door open()
- shut false
- void Door close()
- shut true
62Ex5door.cpp
- class LockableDoor public Door
- public
- LockableDoor()
- bool isLocked() const
- void open()
- void lock()
- void unlock()
- protected
- bool locked
63Ex5door.cpp
- LockableDoorLockableDoor()Door(), locked(true)
-
- bool LockableDoorisLocked() const
- return locked
- void LockableDooropen()
- if (!locked) Dooropen()
- void LockableDoorlock()
- locked true
- void LockableDoorunlock()
- locked false
64Ex5door.cpp
- main()
- Door generic
- LockableDoor bathDoor
- generic.open()
- bathDoor.lock()
- bathDoor.open()
65Ex5door.cpp
- if (!bathDoor.isOpen())
- bathDoor.unlock()
- if (generic.isOpen())
- cout ltlt "generic is open!"ltlt "\n"
- else
- cout ltlt "generic is closed!"ltlt "\n"
- if (bathDoor.isOpen())
- cout ltlt "bathDoor is open!"ltlt "\n"
- else
- cout ltlt "bathDoor is closed!"ltlt "\n"
-
66(No Transcript)
67(No Transcript)
68(No Transcript)
69A complex Example
- Test if the specified file exists
- If yes, find the lines containing include and
output the lines. - Else, do nothing.
70Example ----The files
- Testsrc.cpp (main())(File Structure)
- Fexcept.cpp
- File.cpp
- Srcfile.cpp
- Txtfile.cpp
- Fexcept.h
- File.h
- Srcfile.h
- Txtfile.h
71Example
File_Exception
File
Text_File
Source_File
72(No Transcript)
73(No Transcript)
74(No Transcript)
75(No Transcript)
76(No Transcript)
77(No Transcript)
78(No Transcript)
79(No Transcript)
80(No Transcript)
81(No Transcript)
82(No Transcript)
83(No Transcript)
84(No Transcript)
85(No Transcript)
86(No Transcript)
87Readings
- Readings
- Chapter 6 Sections 6.1.1 - 6.1.2