SlideShare una empresa de Scribd logo
1 de 50
Programming Logic and Design
Eighth Edition
Chapter 11
More Object-Oriented Programming
Concepts
Objectives
2
In this chapter, you will learn about:
• Constructors
• Destructors
• Composition
• Inheritance
• GUI objects
• Exception handling
• The advantages of object-oriented programming
Programming Logic and Design, Eighth Edition
Understanding Constructors
3
• Constructor
– A method that has the same name as the class
– Establishes an object
• Default constructor
– Requires no arguments
– Created automatically by the compiler for every class you
write
• Nondefault constructor
– Requires arguments
Programming Logic and Design, Eighth Edition
Understanding Constructors (continued)
4
• Default constructor for the Employee class
– Establishes one Employee object with the identifier
provided
• Declare constructors to be public so that other
classes can instantiate objects that belong to the
class
• Write any statement you want in a constructor
• Place the constructor anywhere inside the class
– Often, programmers list the constructor first
Programming Logic and Design, Eighth Edition
5
Figure 11-1 Employee class with a
default constructor that sets
hourlyWage and weeklyPay
Programming Logic and Design, Eighth Edition
Understanding
Constructors (continued)
Understanding Constructors (continued)
6
Figure 11-2 Program that declares Employee objects using class in Figure
11-1
Figure 11-3 Output of program
in Figure 11-2
Figure 11-4 Alternate and efficient version of the
Employee class constructor
Programming Logic and Design, Eighth Edition
7
Nondefault Constructors
• Choose to create Employee objects with values
that differ for each employee
– Initialize each Employee with a unique hourlyWage
• Write constructors that receive arguments
– Employee partTimeWorker(8.81)
– Employee
partTimeWorker(valueEnteredByUser)
• When the constructor executes
– Numeric value within the constructor call is passed to
Employee()
Programming Logic and Design, Eighth Edition
Nondefault Constructors (continued)
8
Figure 11-5 Employee constructor that accepts a parameter
• Once you write a constructor for a class, you no
longer receive the automatically written default
constructor
• If a class’s only constructor requires an argument,
you must provide an argument for every object of
that class you create
Programming Logic and Design, Eighth Edition
public Employee(num rate)
setHourlyWage(rate)
return
Overloading Methods and
Constructors
9
• Overload methods
– Write multiple versions of a method with the same name
but different argument lists
• Any method or constructor in a class can be
overloaded
• Can provide as many versions as you want
Programming Logic and Design, Eighth Edition
10
Figure 11-6 Employee class with
overloaded constructors
Programming Logic and Design, Eighth Edition
class Employee
Declarations
private string lastName
private num hourlyWage
private num weeklyPay
public Employee()
Declarations
num DEFAULT_WAGE = 10.00
setHourlyWage(DEFAULT_WAGE)
return
public Employee(num rate)
setHourlyWage(rate)
return
public void setLastName(string name)
lastName = name
return
public void setHourlyWage(num wage)
hourlyWage = wage
calculateWeeklyPay()
return
public string getLastName()
return lastName
public num getHourlyWage()
return hourlyWage
public num getWeeklyPay()
return weeklyPay
private void calculateWeeklyPay()
Declarations
num WORK_WEEK_HOURS = 40
weeklyPay = hourlyWage * WORK_WEEK_HOURS
return
endClass
Default
constructor
Nondefault
constructor
Overloading
Methods
and
Constructors
(continued)
Overloading Methods and
Constructors (continued)
11
Figure 11-7 A third possible Employee class constructor
Programming Logic and Design, Eighth Edition
public Employee(num rate,
string name)
lastName = name
setHourlyWage(rate)
return
Understanding Destructors
12
• Destructor
– A method that contains the actions you require when an
instance of a class is destroyed
• Instance destroyed
– When the object goes out of scope
• If you do not explicitly create a destructor for a
class, one is provided automatically
• Declare a destructor
– Identifier consists of a tilde (˜) followed by the class name
Programming Logic and Design, Eighth Edition
Understanding Destructors (continued)
13
• Cannot provide any parameters to a destructor
– Empty parameter list
• Destructors cannot be overloaded
– Only one destructor per class
• A destructor has no return type
• Programs never explicitly call a destructor
– Invoked automatically
• The last object created is the first object destroyed
Programming Logic and Design, Eighth Edition
Understanding Destructors (continued)
14
Figure 11-8 Employee class with
destructor
Figure 11-9 Program that declares
two Employee objects
Figure 11-10 Output of program in
Figure 11-9
Programming Logic and Design, Eighth Edition
Understanding Composition
15
• When a class contains objects of another class as
data fields, the relationship is called a whole-part
relationship or composition
• Example
– Date that contains a month, day, and year
– Employee class has two Date fields to hold
Employee’s birth date and hire date
• Composition
– Placing a class object within another class object
– Called has-a relationship because one class “has an”
instance of another
Programming Logic and Design, Eighth Edition
Understanding Composition (continued)
16
Figure 11-11 Diagram of typical composition relationships
Programming Logic and Design, Eighth Edition
Understanding Inheritance
17
• Understanding classes helps you organize objects in
real life
• Inheritance
– A principle that enables you to apply your knowledge of a
general category to more specific objects
• Reuse the knowledge you gain about general
categories and apply it to more specific categories
Programming Logic and Design, Eighth Edition
Understanding Inheritance (continued)
18
• Create a class by making it inherit from another
class
– Provided with data fields and methods automatically
– Reuse fields and methods that are already written and
tested
• Employee class
– CommissionEmployee inherits all the attributes and
methods of Employee
Programming Logic and Design, Eighth Edition
Understanding Inheritance (continued)
19
Figure 11-12 An Employee class
Figure 11-13 CommissionEmployee
inherits from Employee
Programming Logic and Design, Eighth Edition
Understanding Inheritance (continued)
20
Figure 11-14 CommissionEmployee class
Programming Logic and Design, Eighth Edition
Understanding Inheritance (continued)
21
• Benefits of CommissionEmployee class
– Save time
– Reduce chance of errors
– Make it easier to understand
– Reduce errors and inconsistencies in shared fields
Programming Logic and Design, Eighth Edition
22
Understanding Inheritance
Terminology
• Base class
– A class that is used as a basis for inheritance
– Also called: Superclass, parent class
• Derived class or extended class
– A class that inherits from a base class
– Also called: Subclass, child class
Programming Logic and Design, Eighth Edition
23
Understanding Inheritance
Terminology (continued)
• Tell which class is the base class and which is the
derived class
– The base class is also called the superclass
– The derived class is also called the subclass
– Use the two classes in a sentence with the phrase “is a”
– Try saying the two class names together
– Compare the class sizes
• The derived class can be further extended
Programming Logic and Design, Eighth Edition
24
Understanding Inheritance
Terminology (continued)
• Ancestors
– The entire list of parent classes from which a child class is
derived
– A child inherits all the members of all its ancestors
– A parent class does not gain any child class members
Programming Logic and Design, Eighth Edition
25
Understanding Inheritance
Terminology (continued)
Figure 11-15 EmployeeDemo application
that declares two Employee objects
Figure 11-16 Output of the
program in Figure 11-15
Programming Logic and Design, Eighth Edition
26
Accessing Private Fields and
Methods of a Parent Class
• It is common for methods to be public but for data
to be private
• When a data field within a class is private:
– No outside class can use it
– Including a child class
• Can be inconvenient
– Inaccessible
Programming Logic and Design, Eighth Edition
27
Accessing Private Fields and Methods
of a Parent Class (continued)
Figure 11-17 Class diagram for HourlyEmployee class
Programming Logic and Design, Eighth Edition
28
Figure 11-18 Implementation of HourlyEmployee class that attempts to access
weeklySalary
Accessing Private Fields and Methods
of a Parent Class (continued)
Programming Logic and Design, Eighth Edition
29
• protected access specifier
– Used when you want no outside classes to be able to use
a data field except classes that are children of the original
class
• If the Employee class’s creator did not foresee
that a field would need to be accessible, then
weeklySalary will remain private
– Possible to correctly set an HourlyEmployee’s weekly
pay using the setWeeklySalary() method
Accessing Private Fields and Methods
of a Parent Class (continued)
Programming Logic and Design, Eighth Edition
30
Figure 11-19 Employee class with a
protected field
Figure 11-20 Employee class with
protected member
Accessing Private Fields and Methods
of a Parent Class (continued)
Programming Logic and Design, Eighth Edition
31
• When a child class accesses a private field of its
parent’s class:
– Modify the parent class to make the field protected
– The child class can use a public method within the parent
class that modifies the field
• Protected access improves performance
– Use protected data members sparingly
• Classes that depend on field names from parent
classes are called fragile because they are prone to
errors
Accessing Private Fields and Methods
of a Parent Class (continued)
Programming Logic and Design, Eighth Edition
32
• Multiple inheritance:
– The capability to inherit from more than one class
• Abstract Class
– A class from which you cannot create any concrete
objects, but from which you can inherit
Accessing Private Fields and Methods
of a Parent Class (continued)
Programming Logic and Design, Eighth Edition
33
Figure 11-21 The HourlyEmployee class when weeklySalary remains private
Accessing Private Fields and Methods
of a Parent Class (continued)
Programming Logic and Design, Eighth Edition
34
Using Inheritance to Achieve
Good Software Design
• You can create powerful computer programs more
easily if many of their components are used either
“as is” or with slight modifications
• Advantages of creating a useful, extendable
superclass:
– Subclass creators save development and testing time
– Superclass code has been tested and is reliable
– Programmers who create or use new subclasses already
understand how the superclass works
– Neither the superclass source code nor the translated
superclass code is changed
Programming Logic and Design, Eighth Edition
35
An Example of Using Predefined
Classes: Creating GUI Objects
• Libraries or packages
– Collections of classes that serve related purposes
• Graphical user interface (GUI) objects
– Created in a visual development environment known as
an IDE (integrated development environment)
– Frames, buttons, labels, and text boxes
– Place within interactive programs so that users can
manipulate them using input devices
Programming Logic and Design, Eighth Edition
36
• Disadvantages of creating your own GUI object
classes:
– Lots of work
– Repetitious
– Components would look different in various applications
• Visual development environment
– Known as an IDE (Integrated Development Environment)
– Create programs by dragging components such as
buttons and labels onto a screen and arranging them
visually
An Example of Using Predefined
Classes: Creating GUI Objects (continued)
Programming Logic and Design, Eighth Edition
Understanding Exception Handling
37
• A lot of effort goes into checking data items to make
sure they are valid and reasonable
• Procedural programs handled errors in various ways
that were effective
– Techniques had some drawbacks
• Object-oriented programming
– New model called exception handling
Programming Logic and Design, Eighth Edition
Drawbacks to Traditional Error-
Handling Techniques
38
• The most often used error-handling outcome in
traditional programming was to terminate the
program
– Unforgiving
– Unstructured
• Forcing the user to reenter data or limiting the
number of chances the user gets to enter correct
data
– May allow no second chance at all
Programming Logic and Design, Eighth Edition
Drawbacks to Traditional Error-
Handling Techniques (continued)
39
Figure 11-22 A method that handles an error in an unstructured manner
Programming Logic and Design, Eighth Edition
Drawbacks to Traditional Error-
Handling Techniques (continued)
40
• More elegant solution
– Looping until the data item becomes valid
• Shortcomings
– Method is not very reusable
– Method is not very flexible
– Only works with interactive programs
Programming Logic and Design, Eighth Edition
Drawbacks to Traditional Error-
Handling Techniques (continued)
41
Figure 11-23 Method that handles an error using a loop
Programming Logic and Design, Eighth Edition
The Object-Oriented Exception-
Handling Model
42
• Exception handling
– A specific group of techniques for handling errors in
object-oriented programs
• Exceptions
– The generic name used for errors in object-oriented
languages
• Try some code that might throw an exception
• If an exception is thrown, it is passed to a block of
code that can catch the exception
Programming Logic and Design, Eighth Edition
43
• throw statement
– Sends an Exception object out of the current code
block or method so it can be handled elsewhere
• try block
– A block of code you attempt to execute while
acknowledging that an exception might occur
– The keyword try, followed by any number of statements
– If a statement in the block causes an exception, the
remaining statements in the try block do not execute
and the try block is abandoned
The Object-Oriented Exception-
Handling Model (continued)
Programming Logic and Design, Eighth Edition
44
• catch block
– A segment of code that can handle an exception
– The keyword catch, followed by parentheses that
contain an Exception type and an identifier
– Statements that take the action you want to use to
handle the error condition
– The endcatch statement indicates the end of the catch
block in the pseudocode
The Object-Oriented Exception-
Handling Model (continued)
Programming Logic and Design, Eighth Edition
45
• General principle of exception handling:
– The method that uses the data should be able to detect
errors, but not be required to handle them
– Handling should be left to the application that uses the
object
• Sunny Day Case
– When there are no exceptions and nothing goes wrong
with a program
The Object-Oriented Exception-
Handling Model (continued)
Programming Logic and Design, Eighth Edition
46
Figure 11-25 A program that contains a
try…catch pair
Figure 11-24 A method that creates
and throws an Exception object
The Object-Oriented Exception-
Handling Model (continued)
Programming Logic and Design, Eighth Edition
Using Built-in Exceptions and Creating
Your Own Exceptions
47
• Many OO languages provide many built-in
Exception types
– Built-in Exceptions in a programming language cannot
cover every condition
• Create your own throwable Exception
– Extend a built-in Exception class
Programming Logic and Design, Eighth Edition
Reviewing the Advantages of
Object-Oriented Programming
48
• Save development time
– Each object automatically includes appropriate, reliable
methods and attributes
• Develop new classes more quickly
– By extending classes that already exist and work
• Use existing objects
– Concentrate only on the interface to those objects
• Polymorphism
– Use reasonable, easy-to-remember names for methods
Programming Logic and Design, Eighth Edition
Summary
49
• A constructor establishes objects and a destructor
destroys them
• Composition
– A class can contain objects of another class as data
members
• Inheritance
– Apply knowledge of a general category to more specific
objects
Programming Logic and Design, Eighth Edition
Summary (continued)
50
• Libraries contain the most useful classes
• Exception-handling techniques are used to handle
errors in object-oriented programs
• Object-oriented programming saves development
time
• Efficiency achieved through both inheritance and
polymorphism
Programming Logic and Design, Eighth Edition

Más contenido relacionado

La actualidad más candente

CIS110 Computer Programming Design Chapter (5)
CIS110 Computer Programming Design Chapter  (5)CIS110 Computer Programming Design Chapter  (5)
CIS110 Computer Programming Design Chapter (5)Dr. Ahmed Al Zaidy
 
Programming Logic and Design: Working with Data
Programming Logic and Design: Working with DataProgramming Logic and Design: Working with Data
Programming Logic and Design: Working with DataNicole Ryan
 
CIS110 Computer Programming Design Chapter (7)
CIS110 Computer Programming Design Chapter  (7)CIS110 Computer Programming Design Chapter  (7)
CIS110 Computer Programming Design Chapter (7)Dr. Ahmed Al Zaidy
 
CIS110 Computer Programming Design Chapter (14)
CIS110 Computer Programming Design Chapter  (14)CIS110 Computer Programming Design Chapter  (14)
CIS110 Computer Programming Design Chapter (14)Dr. Ahmed Al Zaidy
 
Logic Formulation 3
Logic Formulation 3Logic Formulation 3
Logic Formulation 3deathful
 
Logic Formulation 2
Logic Formulation 2Logic Formulation 2
Logic Formulation 2deathful
 
Program logic and design
Program logic and designProgram logic and design
Program logic and designChaffey College
 
Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)Chetan Allapur
 
Data structures & problem solving unit 1 ppt
Data structures & problem solving unit 1 pptData structures & problem solving unit 1 ppt
Data structures & problem solving unit 1 pptaviban
 
9781285852744 ppt ch18
9781285852744 ppt ch189781285852744 ppt ch18
9781285852744 ppt ch18Terry Yoast
 
Csc153 chapter 02
Csc153 chapter 02Csc153 chapter 02
Csc153 chapter 02PCC
 
Csc153 chapter 01
Csc153 chapter 01Csc153 chapter 01
Csc153 chapter 01PCC
 

La actualidad más candente (17)

CIS110 Computer Programming Design Chapter (5)
CIS110 Computer Programming Design Chapter  (5)CIS110 Computer Programming Design Chapter  (5)
CIS110 Computer Programming Design Chapter (5)
 
Programming Logic and Design: Working with Data
Programming Logic and Design: Working with DataProgramming Logic and Design: Working with Data
Programming Logic and Design: Working with Data
 
CIS110 Computer Programming Design Chapter (7)
CIS110 Computer Programming Design Chapter  (7)CIS110 Computer Programming Design Chapter  (7)
CIS110 Computer Programming Design Chapter (7)
 
CIS110 Computer Programming Design Chapter (14)
CIS110 Computer Programming Design Chapter  (14)CIS110 Computer Programming Design Chapter  (14)
CIS110 Computer Programming Design Chapter (14)
 
Unit 4
Unit 4Unit 4
Unit 4
 
Unit 1
Unit 1Unit 1
Unit 1
 
Logic Formulation 3
Logic Formulation 3Logic Formulation 3
Logic Formulation 3
 
Unit 5
Unit 5Unit 5
Unit 5
 
Logic Formulation 2
Logic Formulation 2Logic Formulation 2
Logic Formulation 2
 
Unit i
Unit iUnit i
Unit i
 
Program logic and design
Program logic and designProgram logic and design
Program logic and design
 
Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)Matlab (Presentation on MATLAB)
Matlab (Presentation on MATLAB)
 
Data structures & problem solving unit 1 ppt
Data structures & problem solving unit 1 pptData structures & problem solving unit 1 ppt
Data structures & problem solving unit 1 ppt
 
9781285852744 ppt ch18
9781285852744 ppt ch189781285852744 ppt ch18
9781285852744 ppt ch18
 
Csc153 chapter 02
Csc153 chapter 02Csc153 chapter 02
Csc153 chapter 02
 
Csc153 chapter 01
Csc153 chapter 01Csc153 chapter 01
Csc153 chapter 01
 
Matlab introduction
Matlab introductionMatlab introduction
Matlab introduction
 

Destacado

Destacado (19)

Tecnología educativa
Tecnología educativaTecnología educativa
Tecnología educativa
 
Aprendizaje virtual e learning
Aprendizaje virtual e learningAprendizaje virtual e learning
Aprendizaje virtual e learning
 
Proust
ProustProust
Proust
 
Portfolio Esp. July 2010
Portfolio Esp. July 2010Portfolio Esp. July 2010
Portfolio Esp. July 2010
 
Austin Real Estate Update- Q3 2007
Austin Real Estate Update- Q3 2007Austin Real Estate Update- Q3 2007
Austin Real Estate Update- Q3 2007
 
Hitler e o mein kampf: sucesso enganoso
Hitler e o mein kampf: sucesso enganosoHitler e o mein kampf: sucesso enganoso
Hitler e o mein kampf: sucesso enganoso
 
Comunicacion
ComunicacionComunicacion
Comunicacion
 
Cover
CoverCover
Cover
 
LAS TICS EN EL APRENDIZAJE DEL NIÑO
LAS TICS EN EL APRENDIZAJE DEL NIÑOLAS TICS EN EL APRENDIZAJE DEL NIÑO
LAS TICS EN EL APRENDIZAJE DEL NIÑO
 
Mary Rose Gaughan curriculum vitae
Mary Rose Gaughan curriculum vitaeMary Rose Gaughan curriculum vitae
Mary Rose Gaughan curriculum vitae
 
Os florais perversos de madame de Sade
Os florais perversos de madame de SadeOs florais perversos de madame de Sade
Os florais perversos de madame de Sade
 
E learning
E learningE learning
E learning
 
Lunasanchez elizveth diapositivas
Lunasanchez elizveth diapositivasLunasanchez elizveth diapositivas
Lunasanchez elizveth diapositivas
 
Coal handling stages hiren patel
Coal handling stages   hiren patelCoal handling stages   hiren patel
Coal handling stages hiren patel
 
Communication for presentation
Communication for presentationCommunication for presentation
Communication for presentation
 
11 HR Trends for 2016
11 HR Trends for 201611 HR Trends for 2016
11 HR Trends for 2016
 
Silicon Low Pressure Sensors
Silicon Low Pressure SensorsSilicon Low Pressure Sensors
Silicon Low Pressure Sensors
 
Propuesta Didáctica 2015 Español Primer Grado (Proyecto 3)
Propuesta Didáctica 2015 Español Primer Grado (Proyecto 3)Propuesta Didáctica 2015 Español Primer Grado (Proyecto 3)
Propuesta Didáctica 2015 Español Primer Grado (Proyecto 3)
 
Uv vis spectroscopy
Uv vis spectroscopyUv vis spectroscopy
Uv vis spectroscopy
 

Similar a Chapter 11: Object Oriented Programming Part 2

Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan collegeahmed hmed
 
clean architecture uncle bob AnalysisAndDesign.el.en.pptx
clean architecture uncle bob AnalysisAndDesign.el.en.pptxclean architecture uncle bob AnalysisAndDesign.el.en.pptx
clean architecture uncle bob AnalysisAndDesign.el.en.pptxsaber tabatabaee
 
Hi Navish,Here I attached the feedback form. I personally feel.docx
Hi Navish,Here I attached the feedback form. I personally feel.docxHi Navish,Here I attached the feedback form. I personally feel.docx
Hi Navish,Here I attached the feedback form. I personally feel.docxpooleavelina
 
9781285852744 ppt ch10
9781285852744 ppt ch109781285852744 ppt ch10
9781285852744 ppt ch10Terry Yoast
 
9781285852744 ppt ch10
9781285852744 ppt ch109781285852744 ppt ch10
9781285852744 ppt ch10Terry Yoast
 
9781285852744 ppt ch11
9781285852744 ppt ch119781285852744 ppt ch11
9781285852744 ppt ch11Terry Yoast
 
OOSE Unit 3 PPT.ppt
OOSE Unit 3 PPT.pptOOSE Unit 3 PPT.ppt
OOSE Unit 3 PPT.pptitadmin33
 
Oose unit 3 ppt
Oose unit 3 pptOose unit 3 ppt
Oose unit 3 pptDr VISU P
 
9781285852744 ppt ch09
9781285852744 ppt ch099781285852744 ppt ch09
9781285852744 ppt ch09Terry Yoast
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptxarjun431527
 
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Dimitris Dranidis
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)stanbridge
 
Object-Oriented Design Fundamentals.pptx
Object-Oriented Design Fundamentals.pptxObject-Oriented Design Fundamentals.pptx
Object-Oriented Design Fundamentals.pptxRaflyRizky2
 
CS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPT
CS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPTCS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPT
CS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPTleela rani
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#SyedUmairAli9
 

Similar a Chapter 11: Object Oriented Programming Part 2 (20)

CS1Lesson13-IntroClasses.pptx
CS1Lesson13-IntroClasses.pptxCS1Lesson13-IntroClasses.pptx
CS1Lesson13-IntroClasses.pptx
 
Classes cpp intro thomson bayan college
Classes cpp  intro thomson bayan collegeClasses cpp  intro thomson bayan college
Classes cpp intro thomson bayan college
 
clean architecture uncle bob AnalysisAndDesign.el.en.pptx
clean architecture uncle bob AnalysisAndDesign.el.en.pptxclean architecture uncle bob AnalysisAndDesign.el.en.pptx
clean architecture uncle bob AnalysisAndDesign.el.en.pptx
 
Hi Navish,Here I attached the feedback form. I personally feel.docx
Hi Navish,Here I attached the feedback form. I personally feel.docxHi Navish,Here I attached the feedback form. I personally feel.docx
Hi Navish,Here I attached the feedback form. I personally feel.docx
 
9781285852744 ppt ch10
9781285852744 ppt ch109781285852744 ppt ch10
9781285852744 ppt ch10
 
9781285852744 ppt ch10
9781285852744 ppt ch109781285852744 ppt ch10
9781285852744 ppt ch10
 
9781285852744 ppt ch11
9781285852744 ppt ch119781285852744 ppt ch11
9781285852744 ppt ch11
 
OOSE Unit 3 PPT.ppt
OOSE Unit 3 PPT.pptOOSE Unit 3 PPT.ppt
OOSE Unit 3 PPT.ppt
 
Oose unit 3 ppt
Oose unit 3 pptOose unit 3 ppt
Oose unit 3 ppt
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
9781285852744 ppt ch09
9781285852744 ppt ch099781285852744 ppt ch09
9781285852744 ppt ch09
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
Oops concept on c#
Oops concept on c#Oops concept on c#
Oops concept on c#
 
Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]Design patters java_meetup_slideshare [compatibility mode]
Design patters java_meetup_slideshare [compatibility mode]
 
Lesson 13 object and class
Lesson 13 object and classLesson 13 object and class
Lesson 13 object and class
 
Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)Cs 1023 lec 8 design pattern (week 2)
Cs 1023 lec 8 design pattern (week 2)
 
Object-Oriented Design Fundamentals.pptx
Object-Oriented Design Fundamentals.pptxObject-Oriented Design Fundamentals.pptx
Object-Oriented Design Fundamentals.pptx
 
C# classes objects
C#  classes objectsC#  classes objects
C# classes objects
 
CS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPT
CS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPTCS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPT
CS8592-OOAD-UNIT II-STATIC UML DIAGRAMS PPT
 
Object Oriented Programming with C#
Object Oriented Programming with C#Object Oriented Programming with C#
Object Oriented Programming with C#
 

Más de Nicole Ryan

Testing and Improving Performance
Testing and Improving PerformanceTesting and Improving Performance
Testing and Improving PerformanceNicole Ryan
 
Optimizing a website for search engines
Optimizing a website for search enginesOptimizing a website for search engines
Optimizing a website for search enginesNicole Ryan
 
Javascript programming using the document object model
Javascript programming using the document object modelJavascript programming using the document object model
Javascript programming using the document object modelNicole Ryan
 
Working with Video and Audio
Working with Video and AudioWorking with Video and Audio
Working with Video and AudioNicole Ryan
 
Working with Images
Working with ImagesWorking with Images
Working with ImagesNicole Ryan
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and SetsNicole Ryan
 
Creating Visual Effects and Animation
Creating Visual Effects and AnimationCreating Visual Effects and Animation
Creating Visual Effects and AnimationNicole Ryan
 
Creating and Processing Web Forms
Creating and Processing Web FormsCreating and Processing Web Forms
Creating and Processing Web FormsNicole Ryan
 
Organizing Content with Lists and Tables
Organizing Content with Lists and TablesOrganizing Content with Lists and Tables
Organizing Content with Lists and TablesNicole Ryan
 
Social media and your website
Social media and your websiteSocial media and your website
Social media and your websiteNicole Ryan
 
Working with Links
Working with LinksWorking with Links
Working with LinksNicole Ryan
 
Formatting text with CSS
Formatting text with CSSFormatting text with CSS
Formatting text with CSSNicole Ryan
 
Laying Out Elements with CSS
Laying Out Elements with CSSLaying Out Elements with CSS
Laying Out Elements with CSSNicole Ryan
 
Getting Started with CSS
Getting Started with CSSGetting Started with CSS
Getting Started with CSSNicole Ryan
 
Structure Web Content
Structure Web ContentStructure Web Content
Structure Web ContentNicole Ryan
 
Getting Started with your Website
Getting Started with your WebsiteGetting Started with your Website
Getting Started with your WebsiteNicole Ryan
 
Programming Logic and Design: Arrays
Programming Logic and Design: ArraysProgramming Logic and Design: Arrays
Programming Logic and Design: ArraysNicole Ryan
 
Setting up your development environment
Setting up your development environmentSetting up your development environment
Setting up your development environmentNicole Ryan
 
Dynamic vs static
Dynamic vs staticDynamic vs static
Dynamic vs staticNicole Ryan
 

Más de Nicole Ryan (20)

Testing and Improving Performance
Testing and Improving PerformanceTesting and Improving Performance
Testing and Improving Performance
 
Optimizing a website for search engines
Optimizing a website for search enginesOptimizing a website for search engines
Optimizing a website for search engines
 
Inheritance
InheritanceInheritance
Inheritance
 
Javascript programming using the document object model
Javascript programming using the document object modelJavascript programming using the document object model
Javascript programming using the document object model
 
Working with Video and Audio
Working with Video and AudioWorking with Video and Audio
Working with Video and Audio
 
Working with Images
Working with ImagesWorking with Images
Working with Images
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
 
Creating Visual Effects and Animation
Creating Visual Effects and AnimationCreating Visual Effects and Animation
Creating Visual Effects and Animation
 
Creating and Processing Web Forms
Creating and Processing Web FormsCreating and Processing Web Forms
Creating and Processing Web Forms
 
Organizing Content with Lists and Tables
Organizing Content with Lists and TablesOrganizing Content with Lists and Tables
Organizing Content with Lists and Tables
 
Social media and your website
Social media and your websiteSocial media and your website
Social media and your website
 
Working with Links
Working with LinksWorking with Links
Working with Links
 
Formatting text with CSS
Formatting text with CSSFormatting text with CSS
Formatting text with CSS
 
Laying Out Elements with CSS
Laying Out Elements with CSSLaying Out Elements with CSS
Laying Out Elements with CSS
 
Getting Started with CSS
Getting Started with CSSGetting Started with CSS
Getting Started with CSS
 
Structure Web Content
Structure Web ContentStructure Web Content
Structure Web Content
 
Getting Started with your Website
Getting Started with your WebsiteGetting Started with your Website
Getting Started with your Website
 
Programming Logic and Design: Arrays
Programming Logic and Design: ArraysProgramming Logic and Design: Arrays
Programming Logic and Design: Arrays
 
Setting up your development environment
Setting up your development environmentSetting up your development environment
Setting up your development environment
 
Dynamic vs static
Dynamic vs staticDynamic vs static
Dynamic vs static
 

Último

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...PsychoTech Services
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024Janet Corral
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 

Último (20)

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
IGNOU MSCCFT and PGDCFT Exam Question Pattern: MCFT003 Counselling and Family...
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
General AI for Medical Educators April 2024
General AI for Medical Educators April 2024General AI for Medical Educators April 2024
General AI for Medical Educators April 2024
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 

Chapter 11: Object Oriented Programming Part 2

  • 1. Programming Logic and Design Eighth Edition Chapter 11 More Object-Oriented Programming Concepts
  • 2. Objectives 2 In this chapter, you will learn about: • Constructors • Destructors • Composition • Inheritance • GUI objects • Exception handling • The advantages of object-oriented programming Programming Logic and Design, Eighth Edition
  • 3. Understanding Constructors 3 • Constructor – A method that has the same name as the class – Establishes an object • Default constructor – Requires no arguments – Created automatically by the compiler for every class you write • Nondefault constructor – Requires arguments Programming Logic and Design, Eighth Edition
  • 4. Understanding Constructors (continued) 4 • Default constructor for the Employee class – Establishes one Employee object with the identifier provided • Declare constructors to be public so that other classes can instantiate objects that belong to the class • Write any statement you want in a constructor • Place the constructor anywhere inside the class – Often, programmers list the constructor first Programming Logic and Design, Eighth Edition
  • 5. 5 Figure 11-1 Employee class with a default constructor that sets hourlyWage and weeklyPay Programming Logic and Design, Eighth Edition Understanding Constructors (continued)
  • 6. Understanding Constructors (continued) 6 Figure 11-2 Program that declares Employee objects using class in Figure 11-1 Figure 11-3 Output of program in Figure 11-2 Figure 11-4 Alternate and efficient version of the Employee class constructor Programming Logic and Design, Eighth Edition
  • 7. 7 Nondefault Constructors • Choose to create Employee objects with values that differ for each employee – Initialize each Employee with a unique hourlyWage • Write constructors that receive arguments – Employee partTimeWorker(8.81) – Employee partTimeWorker(valueEnteredByUser) • When the constructor executes – Numeric value within the constructor call is passed to Employee() Programming Logic and Design, Eighth Edition
  • 8. Nondefault Constructors (continued) 8 Figure 11-5 Employee constructor that accepts a parameter • Once you write a constructor for a class, you no longer receive the automatically written default constructor • If a class’s only constructor requires an argument, you must provide an argument for every object of that class you create Programming Logic and Design, Eighth Edition public Employee(num rate) setHourlyWage(rate) return
  • 9. Overloading Methods and Constructors 9 • Overload methods – Write multiple versions of a method with the same name but different argument lists • Any method or constructor in a class can be overloaded • Can provide as many versions as you want Programming Logic and Design, Eighth Edition
  • 10. 10 Figure 11-6 Employee class with overloaded constructors Programming Logic and Design, Eighth Edition class Employee Declarations private string lastName private num hourlyWage private num weeklyPay public Employee() Declarations num DEFAULT_WAGE = 10.00 setHourlyWage(DEFAULT_WAGE) return public Employee(num rate) setHourlyWage(rate) return public void setLastName(string name) lastName = name return public void setHourlyWage(num wage) hourlyWage = wage calculateWeeklyPay() return public string getLastName() return lastName public num getHourlyWage() return hourlyWage public num getWeeklyPay() return weeklyPay private void calculateWeeklyPay() Declarations num WORK_WEEK_HOURS = 40 weeklyPay = hourlyWage * WORK_WEEK_HOURS return endClass Default constructor Nondefault constructor Overloading Methods and Constructors (continued)
  • 11. Overloading Methods and Constructors (continued) 11 Figure 11-7 A third possible Employee class constructor Programming Logic and Design, Eighth Edition public Employee(num rate, string name) lastName = name setHourlyWage(rate) return
  • 12. Understanding Destructors 12 • Destructor – A method that contains the actions you require when an instance of a class is destroyed • Instance destroyed – When the object goes out of scope • If you do not explicitly create a destructor for a class, one is provided automatically • Declare a destructor – Identifier consists of a tilde (˜) followed by the class name Programming Logic and Design, Eighth Edition
  • 13. Understanding Destructors (continued) 13 • Cannot provide any parameters to a destructor – Empty parameter list • Destructors cannot be overloaded – Only one destructor per class • A destructor has no return type • Programs never explicitly call a destructor – Invoked automatically • The last object created is the first object destroyed Programming Logic and Design, Eighth Edition
  • 14. Understanding Destructors (continued) 14 Figure 11-8 Employee class with destructor Figure 11-9 Program that declares two Employee objects Figure 11-10 Output of program in Figure 11-9 Programming Logic and Design, Eighth Edition
  • 15. Understanding Composition 15 • When a class contains objects of another class as data fields, the relationship is called a whole-part relationship or composition • Example – Date that contains a month, day, and year – Employee class has two Date fields to hold Employee’s birth date and hire date • Composition – Placing a class object within another class object – Called has-a relationship because one class “has an” instance of another Programming Logic and Design, Eighth Edition
  • 16. Understanding Composition (continued) 16 Figure 11-11 Diagram of typical composition relationships Programming Logic and Design, Eighth Edition
  • 17. Understanding Inheritance 17 • Understanding classes helps you organize objects in real life • Inheritance – A principle that enables you to apply your knowledge of a general category to more specific objects • Reuse the knowledge you gain about general categories and apply it to more specific categories Programming Logic and Design, Eighth Edition
  • 18. Understanding Inheritance (continued) 18 • Create a class by making it inherit from another class – Provided with data fields and methods automatically – Reuse fields and methods that are already written and tested • Employee class – CommissionEmployee inherits all the attributes and methods of Employee Programming Logic and Design, Eighth Edition
  • 19. Understanding Inheritance (continued) 19 Figure 11-12 An Employee class Figure 11-13 CommissionEmployee inherits from Employee Programming Logic and Design, Eighth Edition
  • 20. Understanding Inheritance (continued) 20 Figure 11-14 CommissionEmployee class Programming Logic and Design, Eighth Edition
  • 21. Understanding Inheritance (continued) 21 • Benefits of CommissionEmployee class – Save time – Reduce chance of errors – Make it easier to understand – Reduce errors and inconsistencies in shared fields Programming Logic and Design, Eighth Edition
  • 22. 22 Understanding Inheritance Terminology • Base class – A class that is used as a basis for inheritance – Also called: Superclass, parent class • Derived class or extended class – A class that inherits from a base class – Also called: Subclass, child class Programming Logic and Design, Eighth Edition
  • 23. 23 Understanding Inheritance Terminology (continued) • Tell which class is the base class and which is the derived class – The base class is also called the superclass – The derived class is also called the subclass – Use the two classes in a sentence with the phrase “is a” – Try saying the two class names together – Compare the class sizes • The derived class can be further extended Programming Logic and Design, Eighth Edition
  • 24. 24 Understanding Inheritance Terminology (continued) • Ancestors – The entire list of parent classes from which a child class is derived – A child inherits all the members of all its ancestors – A parent class does not gain any child class members Programming Logic and Design, Eighth Edition
  • 25. 25 Understanding Inheritance Terminology (continued) Figure 11-15 EmployeeDemo application that declares two Employee objects Figure 11-16 Output of the program in Figure 11-15 Programming Logic and Design, Eighth Edition
  • 26. 26 Accessing Private Fields and Methods of a Parent Class • It is common for methods to be public but for data to be private • When a data field within a class is private: – No outside class can use it – Including a child class • Can be inconvenient – Inaccessible Programming Logic and Design, Eighth Edition
  • 27. 27 Accessing Private Fields and Methods of a Parent Class (continued) Figure 11-17 Class diagram for HourlyEmployee class Programming Logic and Design, Eighth Edition
  • 28. 28 Figure 11-18 Implementation of HourlyEmployee class that attempts to access weeklySalary Accessing Private Fields and Methods of a Parent Class (continued) Programming Logic and Design, Eighth Edition
  • 29. 29 • protected access specifier – Used when you want no outside classes to be able to use a data field except classes that are children of the original class • If the Employee class’s creator did not foresee that a field would need to be accessible, then weeklySalary will remain private – Possible to correctly set an HourlyEmployee’s weekly pay using the setWeeklySalary() method Accessing Private Fields and Methods of a Parent Class (continued) Programming Logic and Design, Eighth Edition
  • 30. 30 Figure 11-19 Employee class with a protected field Figure 11-20 Employee class with protected member Accessing Private Fields and Methods of a Parent Class (continued) Programming Logic and Design, Eighth Edition
  • 31. 31 • When a child class accesses a private field of its parent’s class: – Modify the parent class to make the field protected – The child class can use a public method within the parent class that modifies the field • Protected access improves performance – Use protected data members sparingly • Classes that depend on field names from parent classes are called fragile because they are prone to errors Accessing Private Fields and Methods of a Parent Class (continued) Programming Logic and Design, Eighth Edition
  • 32. 32 • Multiple inheritance: – The capability to inherit from more than one class • Abstract Class – A class from which you cannot create any concrete objects, but from which you can inherit Accessing Private Fields and Methods of a Parent Class (continued) Programming Logic and Design, Eighth Edition
  • 33. 33 Figure 11-21 The HourlyEmployee class when weeklySalary remains private Accessing Private Fields and Methods of a Parent Class (continued) Programming Logic and Design, Eighth Edition
  • 34. 34 Using Inheritance to Achieve Good Software Design • You can create powerful computer programs more easily if many of their components are used either “as is” or with slight modifications • Advantages of creating a useful, extendable superclass: – Subclass creators save development and testing time – Superclass code has been tested and is reliable – Programmers who create or use new subclasses already understand how the superclass works – Neither the superclass source code nor the translated superclass code is changed Programming Logic and Design, Eighth Edition
  • 35. 35 An Example of Using Predefined Classes: Creating GUI Objects • Libraries or packages – Collections of classes that serve related purposes • Graphical user interface (GUI) objects – Created in a visual development environment known as an IDE (integrated development environment) – Frames, buttons, labels, and text boxes – Place within interactive programs so that users can manipulate them using input devices Programming Logic and Design, Eighth Edition
  • 36. 36 • Disadvantages of creating your own GUI object classes: – Lots of work – Repetitious – Components would look different in various applications • Visual development environment – Known as an IDE (Integrated Development Environment) – Create programs by dragging components such as buttons and labels onto a screen and arranging them visually An Example of Using Predefined Classes: Creating GUI Objects (continued) Programming Logic and Design, Eighth Edition
  • 37. Understanding Exception Handling 37 • A lot of effort goes into checking data items to make sure they are valid and reasonable • Procedural programs handled errors in various ways that were effective – Techniques had some drawbacks • Object-oriented programming – New model called exception handling Programming Logic and Design, Eighth Edition
  • 38. Drawbacks to Traditional Error- Handling Techniques 38 • The most often used error-handling outcome in traditional programming was to terminate the program – Unforgiving – Unstructured • Forcing the user to reenter data or limiting the number of chances the user gets to enter correct data – May allow no second chance at all Programming Logic and Design, Eighth Edition
  • 39. Drawbacks to Traditional Error- Handling Techniques (continued) 39 Figure 11-22 A method that handles an error in an unstructured manner Programming Logic and Design, Eighth Edition
  • 40. Drawbacks to Traditional Error- Handling Techniques (continued) 40 • More elegant solution – Looping until the data item becomes valid • Shortcomings – Method is not very reusable – Method is not very flexible – Only works with interactive programs Programming Logic and Design, Eighth Edition
  • 41. Drawbacks to Traditional Error- Handling Techniques (continued) 41 Figure 11-23 Method that handles an error using a loop Programming Logic and Design, Eighth Edition
  • 42. The Object-Oriented Exception- Handling Model 42 • Exception handling – A specific group of techniques for handling errors in object-oriented programs • Exceptions – The generic name used for errors in object-oriented languages • Try some code that might throw an exception • If an exception is thrown, it is passed to a block of code that can catch the exception Programming Logic and Design, Eighth Edition
  • 43. 43 • throw statement – Sends an Exception object out of the current code block or method so it can be handled elsewhere • try block – A block of code you attempt to execute while acknowledging that an exception might occur – The keyword try, followed by any number of statements – If a statement in the block causes an exception, the remaining statements in the try block do not execute and the try block is abandoned The Object-Oriented Exception- Handling Model (continued) Programming Logic and Design, Eighth Edition
  • 44. 44 • catch block – A segment of code that can handle an exception – The keyword catch, followed by parentheses that contain an Exception type and an identifier – Statements that take the action you want to use to handle the error condition – The endcatch statement indicates the end of the catch block in the pseudocode The Object-Oriented Exception- Handling Model (continued) Programming Logic and Design, Eighth Edition
  • 45. 45 • General principle of exception handling: – The method that uses the data should be able to detect errors, but not be required to handle them – Handling should be left to the application that uses the object • Sunny Day Case – When there are no exceptions and nothing goes wrong with a program The Object-Oriented Exception- Handling Model (continued) Programming Logic and Design, Eighth Edition
  • 46. 46 Figure 11-25 A program that contains a try…catch pair Figure 11-24 A method that creates and throws an Exception object The Object-Oriented Exception- Handling Model (continued) Programming Logic and Design, Eighth Edition
  • 47. Using Built-in Exceptions and Creating Your Own Exceptions 47 • Many OO languages provide many built-in Exception types – Built-in Exceptions in a programming language cannot cover every condition • Create your own throwable Exception – Extend a built-in Exception class Programming Logic and Design, Eighth Edition
  • 48. Reviewing the Advantages of Object-Oriented Programming 48 • Save development time – Each object automatically includes appropriate, reliable methods and attributes • Develop new classes more quickly – By extending classes that already exist and work • Use existing objects – Concentrate only on the interface to those objects • Polymorphism – Use reasonable, easy-to-remember names for methods Programming Logic and Design, Eighth Edition
  • 49. Summary 49 • A constructor establishes objects and a destructor destroys them • Composition – A class can contain objects of another class as data members • Inheritance – Apply knowledge of a general category to more specific objects Programming Logic and Design, Eighth Edition
  • 50. Summary (continued) 50 • Libraries contain the most useful classes • Exception-handling techniques are used to handle errors in object-oriented programs • Object-oriented programming saves development time • Efficiency achieved through both inheritance and polymorphism Programming Logic and Design, Eighth Edition