SlideShare a Scribd company logo
1 of 8
10.2 Inheritance
Objects are particularly well-suited to programs that involve modeling real or imaginary
worlds such as graphical user interfaces (modeling windows, files, and folders on
a desktop), simulations (modeling physical objects in the real world and their
interactions), and games (modeling creatures and things in an imagined world).
Objects in the real world (or most simulated worlds) are complex. Suppose we
are implementing a game that simulates a typical university.
It might include many different kinds of objects including places (which are stationary
and may contain other objects), things, and people.
There are many different kinds of people, such as students and professors. All objects in
our game have a name and a location; some objects also have methods for talking and
moving.
We could define classes independently for all of the object types, but this would involve
a lot of duplicate effort.
It would also make it hard to add a new behavior to all of the objects in the
game without modifying many different procedures.
The solution is to define more specialized kinds of objects using the definitions of other
objects. For example, a student is a kind of person.
A student has all the behaviors of a normal person, as well as some behaviors particular
to a studentsuch as choosing a major and graduating.
To implement a student class, we want to reuse methods from the person class without
needing to duplicate them in thestudent implementation.
We call the more specialized class (in this case thestudent class) the subclass and
say student is a subclass of person.
The reused class is known as the superclass, so person is the superclass of student.
A class can have many subclasses but only one superclass.1
Figure 10.2 illustrates some inheritance relationships for a university simulator.
The arrows point from subclasses to their superclass.
A class may be both a subclass to another class, and a superclass to a different class. For
example,person is a subclass of movable-object, but a superclass of student andprofessor.
Figure 10.2: Inheritance hierarchy.
Our goal is to be able to reuse superclass methods in subclasses.
When a method is invoked in a subclass, if the subclass does not provide a definition of
the method, then the definition of the method in the superclass is used.
This can continue up the superclass chain. For instance, student is a subclass of person,
which is a subclass of movable-object, which is a subclass of sim-object(simulation object),
which is the superclass of all classes in the simulator.
Hence, if the sim-object class defines a get-name method, when the get-namemethod
is invoked on a student object, the implementation of get-name in thesim-object class will
be used (as long as neither person nor movable-objectdefines its own get-name method).
When one class implementation uses the methods from another class we say the
subclass inherits from the superclass.
Inheritance is a powerful way to obtain many different objects with a small amount of
code.
10.2.1 Implementing Subclasses
To implement inheritance we change class definitions so that if a requested method is
not defined by the subclass, the method defined by its superclass will be used.
The make-sub-object procedure does this. It takes two inputs, a superclass object and the
object dispatching procedure of the subclass, and produces an instance of the subclass
which is a procedure that takes a message as input and outputs the
method corresponding to that message.
If the method is defined by the subclass, the result will be the subclass method. If the
method is not defined by the subclass, it will be the superclass method.
(define (make-sub-object
(lambda (message)
super subproc)
(let ((method (subproc
(if method method (super message)))))
message)))
When an object produced by (make-sub-object obj proc) is applied to a message, it
first applies the subclass dispatch procedure to the message to find an appropriate
method if one is defined.
If no method is defined by the subclass implementation, it evaluates to (super message),
the method associated with themessage in the superclass.
References to self. It is useful to add an extra parameter to all methods so the object
on which the method was invoked is visible.
Otherwise, the object will lose its special behaviors as it is moves up the superclasses.
We call this the selfobject (in some languages it is called the this object instead).
To support this, we modify the ask procedure to pass in the object parameter to
the method:
(define (ask object message . args) (apply (object message) object
args))
All methods now take the self object as their first parameter, and may take
additional parameters. So, the counter constructor is defined as:
(define (make-counter) (let ((count 0))
(lambda (message)
(cond
((eq? message 'get-count) (lambda (self) count))
((eq? message 'reset!) (lambda (self) (set! count 0)))
((eq? message 'next!) (lambda (self) (set! count (+ 1 count))))
(else (error "Unrecognized message"))))))
Subclassing counter. Since subclass objects cannot see the instance variables of their
superclass objects directly, if we want to provide a versatile counter class we need to also
provide a set-count! method for setting the value of the counter to an arbitrary value.
For reasons that will become clear later, we should useset-count! everywhere the value of
the count variable is changed instead of setting it directly:
(define (make-counter)
(let ((count 0))
(lambda (message)
(cond 'get-count)
(lambda (self)
count))
val) (set! count
val)))
((eq? message
'set-count!) (lambda (self((eq? message
(else (error "Unrecognized message"))))))
Previously, we defined make-adjustable-counter by repeating all the code
frommake- counter and adding an adjust! method.
With inheritance, we can definemake-adjustable-counter as a
counter without repeating any code:
subclass of make-
(define (make-adjustable-counter)
(make-sub-object
(make-counter)
(lambda (message)
(cond 'adjust!)
val) 'get-count)
val))))
((eq? message
(lambda (self
(ask self 'set-count! (+ (ask self
(else false)))))
We use make-sub-object to create an object that inherits the behaviors from one
class, and extends those behaviors by defining new methods in the subclass
implementation.
((eq? message 'reset!) (lambda (self) (ask self 'set-count! 0)))
((eq? message 'next!)
(lambda (self) (ask self 'set-count! (+ 1 (ask self 'current)))))
10.2.2 Overriding methods
In addition to adding new methods, subclasses can replace the definitions of methods
defined in the superclass.
When a subclass replaces a method defined by its superclass, then the subclass method
the superclass method. When the method is invoked on a subclass object, the
new method will be used.
For example, we can define a subclass of reversible-counter that is not allowed to
have negative counter values.
If the counter would reach a negative number, instead of setting the counter to the new
value, it produces an error message and maintains the counter at zero. We do this by
overriding the set-count! method, replacing the superclass implementation of the
method with a new implementation.
(define (make-positive-counter)
(make-subobject
(make-reversible-counter)
(lambda (message)
(cond 'set-count!)
((eq? message
(lambda (self val) (if (< val 0) (error "Negative count")
...)))
(else false)))))
What should go in place of the ……? When the value to set the count to is not negative,
what should happen is the count is set as it would be by the superclassset-count! method.
In the positive-counter code though, there is no way to access the count variable since it is
in the superclass procedure's application environment.
There is also no way to invoke the superclass' set-count! method since it has been
overridden by positive-counter.
The solution is to provide a way for the subclass object to obtain its superclass object.
We can do this by adding a get-super method to the object produced bymake-sub-object:
(define (make-sub-object
(lambda (message)
super subproc)
(if (eq? message 'get-super)
(lambda (self) super)
(let ((method (subproc
(if method method (super message))))))
message)))
Thus, when an object produced by make-sub-object is passed the get-supermessage it
returns a method that produces the super object.
The rest of the procedure is the same as before, so for every other message it behaves
like the earlier make-sub-object procedure.

More Related Content

What's hot

Unit4 (2)
Unit4 (2)Unit4 (2)
Unit4 (2)
mrecedu
 
Anton Kasyanov, Introduction to Python, Lecture3
Anton Kasyanov, Introduction to Python, Lecture3Anton Kasyanov, Introduction to Python, Lecture3
Anton Kasyanov, Introduction to Python, Lecture3
Anton Kasyanov
 
웹기반 Ajax개발을 위한 프레임워크 - metaworks3 (메타웍스3)
웹기반 Ajax개발을 위한 프레임워크 - metaworks3 (메타웍스3)웹기반 Ajax개발을 위한 프레임워크 - metaworks3 (메타웍스3)
웹기반 Ajax개발을 위한 프레임워크 - metaworks3 (메타웍스3)
uEngine Solutions
 

What's hot (20)

Unit4 (2)
Unit4 (2)Unit4 (2)
Unit4 (2)
 
String in java
String in javaString in java
String in java
 
Arrays string handling java packages
Arrays string handling java packagesArrays string handling java packages
Arrays string handling java packages
 
The Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael MaganaThe Ruby Object Model by Rafael Magana
The Ruby Object Model by Rafael Magana
 
Objects by Sufian Idris
Objects by Sufian IdrisObjects by Sufian Idris
Objects by Sufian Idris
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 
Action Script
Action ScriptAction Script
Action Script
 
Only oop
Only oopOnly oop
Only oop
 
Chain of responsibility
Chain of responsibilityChain of responsibility
Chain of responsibility
 
Lightning talk
Lightning talkLightning talk
Lightning talk
 
Java Beans Unit 4(Part 1)
Java Beans Unit 4(Part 1)Java Beans Unit 4(Part 1)
Java Beans Unit 4(Part 1)
 
Anton Kasyanov, Introduction to Python, Lecture3
Anton Kasyanov, Introduction to Python, Lecture3Anton Kasyanov, Introduction to Python, Lecture3
Anton Kasyanov, Introduction to Python, Lecture3
 
Java String
Java StringJava String
Java String
 
Interesting Facts About Javascript
Interesting Facts About JavascriptInteresting Facts About Javascript
Interesting Facts About Javascript
 
Lecture 7
Lecture 7Lecture 7
Lecture 7
 
Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
 
String, string builder, string buffer
String, string builder, string bufferString, string builder, string buffer
String, string builder, string buffer
 
웹기반 Ajax개발을 위한 프레임워크 - metaworks3 (메타웍스3)
웹기반 Ajax개발을 위한 프레임워크 - metaworks3 (메타웍스3)웹기반 Ajax개발을 위한 프레임워크 - metaworks3 (메타웍스3)
웹기반 Ajax개발을 위한 프레임워크 - metaworks3 (메타웍스3)
 
Javascript Objects Deep Dive
Javascript Objects Deep DiveJavascript Objects Deep Dive
Javascript Objects Deep Dive
 

Viewers also liked

Viewers also liked (19)

mutable pairs_and_lists
mutable pairs_and_listsmutable pairs_and_lists
mutable pairs_and_lists
 
processes
processesprocesses
processes
 
histry of_computing_machines
histry of_computing_machineshistry of_computing_machines
histry of_computing_machines
 
expressions
expressionsexpressions
expressions
 
developing complex_programs
developing complex_programsdeveloping complex_programs
developing complex_programs
 
languages
languageslanguages
languages
 
parser
parserparser
parser
 
decisions
decisionsdecisions
decisions
 
modeling computing
modeling computingmodeling computing
modeling computing
 
1.3 applications, issues
1.3 applications, issues1.3 applications, issues
1.3 applications, issues
 
recursive transition_networks
recursive transition_networksrecursive transition_networks
recursive transition_networks
 
measuring computing_power
measuring computing_powermeasuring computing_power
measuring computing_power
 
Regular expressions h1
Regular expressions h1Regular expressions h1
Regular expressions h1
 
Binary trees
Binary treesBinary trees
Binary trees
 
Quicksort
QuicksortQuicksort
Quicksort
 
Normal forms cfg
Normal forms   cfgNormal forms   cfg
Normal forms cfg
 
TM - Techniques
TM - TechniquesTM - Techniques
TM - Techniques
 
Pumping lemma for regular set h1
Pumping lemma for regular set h1Pumping lemma for regular set h1
Pumping lemma for regular set h1
 
Basics of data structure
Basics of data structureBasics of data structure
Basics of data structure
 

Similar to inheritance

Preexisting code, please useMain.javapublic class Main { p.pdf
Preexisting code, please useMain.javapublic class Main {    p.pdfPreexisting code, please useMain.javapublic class Main {    p.pdf
Preexisting code, please useMain.javapublic class Main { p.pdf
rd1742
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
Connex
 

Similar to inheritance (20)

Preexisting code, please useMain.javapublic class Main { p.pdf
Preexisting code, please useMain.javapublic class Main {    p.pdfPreexisting code, please useMain.javapublic class Main {    p.pdf
Preexisting code, please useMain.javapublic class Main { p.pdf
 
Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear Inheritance and Polymorphism in java simple and clear
Inheritance and Polymorphism in java simple and clear
 
java_inheritance.pdf
java_inheritance.pdfjava_inheritance.pdf
java_inheritance.pdf
 
Class notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritanceClass notes(week 6) on inheritance and multiple inheritance
Class notes(week 6) on inheritance and multiple inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
JAVA Polymorphism
JAVA PolymorphismJAVA Polymorphism
JAVA Polymorphism
 
Delphi qa
Delphi qaDelphi qa
Delphi qa
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Classes2
Classes2Classes2
Classes2
 
CHAPTER 1 - OVERVIEW OOP.ppt
CHAPTER 1 - OVERVIEW OOP.pptCHAPTER 1 - OVERVIEW OOP.ppt
CHAPTER 1 - OVERVIEW OOP.ppt
 
Utility Classes
Utility ClassesUtility Classes
Utility Classes
 
6. Compile And Run
6. Compile And Run6. Compile And Run
6. Compile And Run
 
Object Oriented PHP - PART-1
Object Oriented PHP - PART-1Object Oriented PHP - PART-1
Object Oriented PHP - PART-1
 
Java basics
Java basicsJava basics
Java basics
 
MODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptxMODULE_3_Methods and Classes Overloading.pptx
MODULE_3_Methods and Classes Overloading.pptx
 
Copy on write
Copy on writeCopy on write
Copy on write
 
Classes1
Classes1Classes1
Classes1
 
Oop features java presentationshow
Oop features java presentationshowOop features java presentationshow
Oop features java presentationshow
 
Abstract
AbstractAbstract
Abstract
 
The Uniform Access Principle
The Uniform Access PrincipleThe Uniform Access Principle
The Uniform Access Principle
 

More from Rajendran

More from Rajendran (20)

Element distinctness lower bounds
Element distinctness lower boundsElement distinctness lower bounds
Element distinctness lower bounds
 
Scheduling with Startup and Holding Costs
Scheduling with Startup and Holding CostsScheduling with Startup and Holding Costs
Scheduling with Startup and Holding Costs
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower bounds
 
Red black tree
Red black treeRed black tree
Red black tree
 
Hash table
Hash tableHash table
Hash table
 
Medians and order statistics
Medians and order statisticsMedians and order statistics
Medians and order statistics
 
Proof master theorem
Proof master theoremProof master theorem
Proof master theorem
 
Recursion tree method
Recursion tree methodRecursion tree method
Recursion tree method
 
Recurrence theorem
Recurrence theoremRecurrence theorem
Recurrence theorem
 
Master method
Master method Master method
Master method
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Hash tables
Hash tablesHash tables
Hash tables
 
Lower bound
Lower boundLower bound
Lower bound
 
Master method theorem
Master method theoremMaster method theorem
Master method theorem
 
Greedy algorithms
Greedy algorithmsGreedy algorithms
Greedy algorithms
 
Longest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm AnalysisLongest common subsequences in Algorithm Analysis
Longest common subsequences in Algorithm Analysis
 
Dynamic programming in Algorithm Analysis
Dynamic programming in Algorithm AnalysisDynamic programming in Algorithm Analysis
Dynamic programming in Algorithm Analysis
 
Average case Analysis of Quicksort
Average case Analysis of QuicksortAverage case Analysis of Quicksort
Average case Analysis of Quicksort
 
Np completeness
Np completenessNp completeness
Np completeness
 
computer languages
computer languagescomputer languages
computer languages
 

Recently uploaded

Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Google Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptxGoogle Gemini An AI Revolution in Education.pptx
Google Gemini An AI Revolution in Education.pptx
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
Beyond_Borders_Understanding_Anime_and_Manga_Fandom_A_Comprehensive_Audience_...
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
Philosophy of china and it's charactistics
Philosophy of china and it's charactisticsPhilosophy of china and it's charactistics
Philosophy of china and it's charactistics
 
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7Call Girls in  Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
Call Girls in Uttam Nagar (delhi) call me [🔝9953056974🔝] escort service 24X7
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 

inheritance

  • 1. 10.2 Inheritance Objects are particularly well-suited to programs that involve modeling real or imaginary worlds such as graphical user interfaces (modeling windows, files, and folders on a desktop), simulations (modeling physical objects in the real world and their interactions), and games (modeling creatures and things in an imagined world). Objects in the real world (or most simulated worlds) are complex. Suppose we are implementing a game that simulates a typical university. It might include many different kinds of objects including places (which are stationary and may contain other objects), things, and people. There are many different kinds of people, such as students and professors. All objects in our game have a name and a location; some objects also have methods for talking and moving. We could define classes independently for all of the object types, but this would involve a lot of duplicate effort. It would also make it hard to add a new behavior to all of the objects in the game without modifying many different procedures. The solution is to define more specialized kinds of objects using the definitions of other objects. For example, a student is a kind of person.
  • 2. A student has all the behaviors of a normal person, as well as some behaviors particular to a studentsuch as choosing a major and graduating. To implement a student class, we want to reuse methods from the person class without needing to duplicate them in thestudent implementation. We call the more specialized class (in this case thestudent class) the subclass and say student is a subclass of person. The reused class is known as the superclass, so person is the superclass of student. A class can have many subclasses but only one superclass.1 Figure 10.2 illustrates some inheritance relationships for a university simulator. The arrows point from subclasses to their superclass. A class may be both a subclass to another class, and a superclass to a different class. For example,person is a subclass of movable-object, but a superclass of student andprofessor. Figure 10.2: Inheritance hierarchy.
  • 3. Our goal is to be able to reuse superclass methods in subclasses. When a method is invoked in a subclass, if the subclass does not provide a definition of the method, then the definition of the method in the superclass is used. This can continue up the superclass chain. For instance, student is a subclass of person, which is a subclass of movable-object, which is a subclass of sim-object(simulation object), which is the superclass of all classes in the simulator. Hence, if the sim-object class defines a get-name method, when the get-namemethod is invoked on a student object, the implementation of get-name in thesim-object class will be used (as long as neither person nor movable-objectdefines its own get-name method). When one class implementation uses the methods from another class we say the subclass inherits from the superclass. Inheritance is a powerful way to obtain many different objects with a small amount of code.
  • 4. 10.2.1 Implementing Subclasses To implement inheritance we change class definitions so that if a requested method is not defined by the subclass, the method defined by its superclass will be used. The make-sub-object procedure does this. It takes two inputs, a superclass object and the object dispatching procedure of the subclass, and produces an instance of the subclass which is a procedure that takes a message as input and outputs the method corresponding to that message. If the method is defined by the subclass, the result will be the subclass method. If the method is not defined by the subclass, it will be the superclass method. (define (make-sub-object (lambda (message) super subproc) (let ((method (subproc (if method method (super message))))) message))) When an object produced by (make-sub-object obj proc) is applied to a message, it first applies the subclass dispatch procedure to the message to find an appropriate method if one is defined. If no method is defined by the subclass implementation, it evaluates to (super message), the method associated with themessage in the superclass.
  • 5. References to self. It is useful to add an extra parameter to all methods so the object on which the method was invoked is visible. Otherwise, the object will lose its special behaviors as it is moves up the superclasses. We call this the selfobject (in some languages it is called the this object instead). To support this, we modify the ask procedure to pass in the object parameter to the method: (define (ask object message . args) (apply (object message) object args)) All methods now take the self object as their first parameter, and may take additional parameters. So, the counter constructor is defined as: (define (make-counter) (let ((count 0)) (lambda (message) (cond ((eq? message 'get-count) (lambda (self) count)) ((eq? message 'reset!) (lambda (self) (set! count 0))) ((eq? message 'next!) (lambda (self) (set! count (+ 1 count)))) (else (error "Unrecognized message")))))) Subclassing counter. Since subclass objects cannot see the instance variables of their superclass objects directly, if we want to provide a versatile counter class we need to also provide a set-count! method for setting the value of the counter to an arbitrary value.
  • 6. For reasons that will become clear later, we should useset-count! everywhere the value of the count variable is changed instead of setting it directly: (define (make-counter) (let ((count 0)) (lambda (message) (cond 'get-count) (lambda (self) count)) val) (set! count val))) ((eq? message 'set-count!) (lambda (self((eq? message (else (error "Unrecognized message")))))) Previously, we defined make-adjustable-counter by repeating all the code frommake- counter and adding an adjust! method. With inheritance, we can definemake-adjustable-counter as a counter without repeating any code: subclass of make- (define (make-adjustable-counter) (make-sub-object (make-counter) (lambda (message) (cond 'adjust!) val) 'get-count) val)))) ((eq? message (lambda (self (ask self 'set-count! (+ (ask self (else false))))) We use make-sub-object to create an object that inherits the behaviors from one class, and extends those behaviors by defining new methods in the subclass implementation. ((eq? message 'reset!) (lambda (self) (ask self 'set-count! 0))) ((eq? message 'next!) (lambda (self) (ask self 'set-count! (+ 1 (ask self 'current)))))
  • 7. 10.2.2 Overriding methods In addition to adding new methods, subclasses can replace the definitions of methods defined in the superclass. When a subclass replaces a method defined by its superclass, then the subclass method the superclass method. When the method is invoked on a subclass object, the new method will be used. For example, we can define a subclass of reversible-counter that is not allowed to have negative counter values. If the counter would reach a negative number, instead of setting the counter to the new value, it produces an error message and maintains the counter at zero. We do this by overriding the set-count! method, replacing the superclass implementation of the method with a new implementation. (define (make-positive-counter) (make-subobject (make-reversible-counter) (lambda (message) (cond 'set-count!) ((eq? message (lambda (self val) (if (< val 0) (error "Negative count") ...))) (else false))))) What should go in place of the ……? When the value to set the count to is not negative, what should happen is the count is set as it would be by the superclassset-count! method. In the positive-counter code though, there is no way to access the count variable since it is in the superclass procedure's application environment.
  • 8. There is also no way to invoke the superclass' set-count! method since it has been overridden by positive-counter. The solution is to provide a way for the subclass object to obtain its superclass object. We can do this by adding a get-super method to the object produced bymake-sub-object: (define (make-sub-object (lambda (message) super subproc) (if (eq? message 'get-super) (lambda (self) super) (let ((method (subproc (if method method (super message)))))) message))) Thus, when an object produced by make-sub-object is passed the get-supermessage it returns a method that produces the super object. The rest of the procedure is the same as before, so for every other message it behaves like the earlier make-sub-object procedure.