SlideShare a Scribd company logo
1 of 39
Data Structures Using Java 1
Chapter 2
Inheritance and Exception Handling
Data Structures Using Java 2
Chapter Objectives
• Learn about inheritance
• Learn about sub- and superclasses
• Explore how to override the methods of a
superclass
• Examine how constructors of super- and
subclasses work
• Examine abstract classes
• Learn about composition
Data Structures Using Java 3
Chapter Objectives
• Learn about exceptions
• Become aware of exception classes and their
hierarchy
• Learn about checked and unchecked exceptions
• Learn how to handle exceptions within a program
• Examine try/catch blocks
• Discover how to throw and rethrow an exception
Data Structures Using Java 4
Inheritance
• “is-a” relationship
• Single inheritance
– subclass derived from one existing class (superclass)
• Multiple inheritance
– Subclass derived from more than one superclass
– Not supported by Java
– In Java, a class can only extend definition of one class
Data Structures Using Java 5
Inheritance
Data Structures Using Java 6
Inheritance
• Private members of superclass
– private to superclass; cannot be accessed
directly by subclass
• Subclass can override method of superclass;
redefinition applies only to object of
subclass
Data Structures Using Java 7
Inheritance
• To write method definition of subclass to specify
call to public method of superclass
– If subclass overrides public method of superclass, to
specify call to public method of superclass:
super.MethodName(parameter list)
– If subclass does not override public method of
superclass, to specify call to public method of
superclass: MethodName(parameter list)
Data Structures Using Java 8
Defining Constructor of Subclass
• Call to constructor of superclass
– must be first statement
– specified by: super parameter list
Data Structures Using Java 9
The class Object
• Directly or indirectly superclass of every
class in Java
• Public members of class Object can be
overridden/invoked by object of any class
type
Data Structures Using Java 10
The class Object
Data Structures Using Java 11
Objects of Superclasses and
Subclasses
• Cannot automatically make reference variable of
subclass type point to object of superclass
• Dynamic binding: method executed determined at
execution time, not compile time
• Operator instanceof : determines whether
reference variable that points to object is of
particular class type
• ClassCastException thrown if class cast is not
allowed
Data Structures Using Java 12
The Operator instanceof
• Reference of superclass type can point to
objects of its subclass
• Can determine if a reference variable points
to an object using operator instanceof
Data Structures Using Java 13
Abstract Methods and Classes
• Abstract method: method that has only the
heading with no body
– must be declared abstract
• Abstract class: class that is declared with the
reserved word abstract in its heading
Data Structures Using Java 14
Abstract Class
• Can contain instance variables,
constructors, finalizer, abstract and
nonabstract methods
• Cannot instantiate object of abstract class
type; can only declare reference variable
• Can instantiate object of subclass of abstract
class, but only if subclass gives definitions
of all abstract methods of superclass
Data Structures Using Java 15
Composition
• Another way to relate two classes
• One or more members of a class are objects
of another class type
• “has-a” relation between classes
Data Structures Using Java 16
Exception
• Definition: an occurrence of an undesirable
situation that can be detected during
program execution
• Examples
– division by zero
– trying to open an input file that does not exist is
an exception
– an array index that goes out of bounds
Data Structures Using Java 17
Java Exception Hierarchy
Data Structures Using Java 18
The class Throwable
Data Structures Using Java 19
The class Exception and its
Subclasses from java.lang
Data Structures Using Java 20
The class Exception and its
Subclasses from java.util
Data Structures Using Java 21
The class Exception and its
Subclasses from java.io
Data Structures Using Java 22
Java’s Exception Class
• Class Exception
– Subclass of class Throwable
– superclass of classes designed to handle exceptions
• Various types of exceptions
– I/O exceptions
– Number format exceptions
– File not found exceptions
– Array index out of bounds exception
• Various exceptions categorized into separate
classes and contained in various packages
Data Structures Using Java 23
The class Exception and its
Constructors
Data Structures Using Java 24
Java Exception Classes
Data Structures Using Java 25
Exceptions Thrown by Methods
Data Structures Using Java 26
Exceptions Thrown by Methods
Data Structures Using Java 27
Checked Exceptions
• Checked Exception: any exception that can
be analyzed by the compiler
• Example
– IOExceptions
Data Structures Using Java 28
Unchecked Exceptions
• Unchecked Exception: exception that cannot be
analyzed when the program compiles (must be
checked for by programmer)
• Examples
– Division by zero
– Array index out of hounds
• Syntax
– throws ExceptionType1, ExceptionType2, …
*ExceptionType1, ExceptionType2, etc are names of exception
classes
Data Structures Using Java 29
Handling Exceptions within a
Program
• try/catch/finally block used to handle exceptions
within a program
• try block:
– Includes statements that may generate an exception
– Includes statements that should not be executed if an
exception occurs
– followed by zero or more catch blocks
– May or may not be followed by finally block
Data Structures Using Java 30
Handling Exceptions within a
Program
• Catch block:
– heading specifies type of exception it can catch
– contains exception handler; completely handles
exception
– can catch all exceptions of a specific type or all types of
exceptions
– may or may not be followed by a finally block
• Finally block
– Code contained in this block always executes
– try block with no catch block has finally block
Data Structures Using Java 31
Order of Catch Blocks
• If exception in try block caught by first
catch block, reaming catch blocks ignored
• Must be careful about order catch blocks
are listed
Data Structures Using Java 32
Rethrowing and Throwing an
Exception
• Useful when
– Catch block catches exception but is unable to
handle it
– Catch block decides exception should be
handled by calling environment
• Allows programmer to provide exception
handling code in one place
Data Structures Using Java 33
Exception Handling Techniques
• Terminate program
– Output appropriate error message upon termination
• Fix error and continue
– Repeatedly get user input/output appropriate error
message until valid value is entered
• Log error and continue
– Write error messages to file and continue with program
execution
Data Structures Using Java 34
Creating Your Own Exception
Classes
• Exception class you define extends class
Exception or one of its subclasses
• Syntax to throw your own exception object
– throw new ExceptionClassName(messageString);
Data Structures Using Java 35
Programming Example: Grade
Report
• Main algorithm
– Declare variables
– Open input file
– Open output file
– Get number students registered and tuition rate
– Load students’ data
– Print grade reports
Data Structures Using Java 36
Programming Example: Grade
Report
• Components: student, course
• Operations on course
– Set course information
– Print course information
– Show credit hours
– Show course number
– Show grade
Data Structures Using Java 37
Programming Example: Grade
Report
• Operations on student
– Set student information
– Print student information
– Calculate number of credit hours taken
– Calculate GPA
– Calculate billing amount
– Sort the courses according to the course number
Data Structures Using Java 38
Chapter Summary
• Inheritance
– Single and multiple
– Rules and Uses
– Superclasses/subclasses (objects)
– Overriding/overloading methods
• The class Object
– Constructors
– Rules
• Abstract methods and classes
Data Structures Using Java 39
Chapter Summary
• Composition
• Exception
• Checked and Unchecked Exceptions
• Creating your own exception classes
• Exception handling techniques
• Handling exceptions within a program

More Related Content

What's hot (20)

Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
Inner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVAInner Classes & Multi Threading in JAVA
Inner Classes & Multi Threading in JAVA
 
Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3Statics in java | Constructors | Exceptions in Java | String in java| class 3
Statics in java | Constructors | Exceptions in Java | String in java| class 3
 
Introducing classes
Introducing classesIntroducing classes
Introducing classes
 
Java(inheritance)
Java(inheritance)Java(inheritance)
Java(inheritance)
 
Java static keyword
Java static keywordJava static keyword
Java static keyword
 
Inner class
Inner classInner class
Inner class
 
Packages
PackagesPackages
Packages
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
java-06inheritance
java-06inheritancejava-06inheritance
java-06inheritance
 
Inheritance in JAVA PPT
Inheritance  in JAVA PPTInheritance  in JAVA PPT
Inheritance in JAVA PPT
 
Inner classes
Inner classesInner classes
Inner classes
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Uniform and Safe Metaclass Composition
Uniform and Safe Metaclass CompositionUniform and Safe Metaclass Composition
Uniform and Safe Metaclass Composition
 
Object oriented programming 3 object oriented concepts
Object oriented programming 3 object oriented conceptsObject oriented programming 3 object oriented concepts
Object oriented programming 3 object oriented concepts
 
Inheritance and Polymorphism
Inheritance and PolymorphismInheritance and Polymorphism
Inheritance and Polymorphism
 
Metaprogramming ruby
Metaprogramming rubyMetaprogramming ruby
Metaprogramming ruby
 
JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O JAVA PROGRAMMING – Packages - Stream based I/O
JAVA PROGRAMMING – Packages - Stream based I/O
 
javainheritance
javainheritancejavainheritance
javainheritance
 

Similar to Chap02

chapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programmingchapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programmingWondimuBantihun1
 
SystemVerilog_Classes.pdf
SystemVerilog_Classes.pdfSystemVerilog_Classes.pdf
SystemVerilog_Classes.pdfssusere9cd04
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingNithyaN19
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxethiouniverse
 
Abstraction in java.pptx
Abstraction in java.pptxAbstraction in java.pptx
Abstraction in java.pptxAsifMulani17
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with javaSujit Kumar
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
Java lec class, objects and constructors
Java lec class, objects and constructorsJava lec class, objects and constructors
Java lec class, objects and constructorsJan Niño Acierto
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.pptAshwathGupta
 

Similar to Chap02 (20)

chapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programmingchapter 5 concepts of object oriented programming
chapter 5 concepts of object oriented programming
 
SystemVerilog_Classes.pdf
SystemVerilog_Classes.pdfSystemVerilog_Classes.pdf
SystemVerilog_Classes.pdf
 
Java Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overridingJava Inheritance - sub class constructors - Method overriding
Java Inheritance - sub class constructors - Method overriding
 
Object Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptxObject Oriented Programming Tutorial.pptx
Object Oriented Programming Tutorial.pptx
 
Java chapter 5
Java chapter 5Java chapter 5
Java chapter 5
 
Abstraction in java.pptx
Abstraction in java.pptxAbstraction in java.pptx
Abstraction in java.pptx
 
Java
JavaJava
Java
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Introduction to OOP with java
Introduction to OOP with javaIntroduction to OOP with java
Introduction to OOP with java
 
Inheritance and interface
Inheritance and interfaceInheritance and interface
Inheritance and interface
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
Unit 4
Unit 4Unit 4
Unit 4
 
Java lec class, objects and constructors
Java lec class, objects and constructorsJava lec class, objects and constructors
Java lec class, objects and constructors
 
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
5. OBJECT ORIENTED PROGRAMMING USING JAVA - INHERITANCE.ppt
 
DAY_1.4.pptx
DAY_1.4.pptxDAY_1.4.pptx
DAY_1.4.pptx
 
Unit 3
Unit 3Unit 3
Unit 3
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Java Programming Fundamentals
Java Programming Fundamentals Java Programming Fundamentals
Java Programming Fundamentals
 
core_java.ppt
core_java.pptcore_java.ppt
core_java.ppt
 
OOPS Characteristics
OOPS CharacteristicsOOPS Characteristics
OOPS Characteristics
 

More from Jotham Gadot

Database using oracle 10g
Database using oracle 10gDatabase using oracle 10g
Database using oracle 10gJotham Gadot
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ beginner's guide ch08
C++ beginner's guide ch08Jotham Gadot
 
01 introduction-to-computers
01 introduction-to-computers01 introduction-to-computers
01 introduction-to-computersJotham Gadot
 
Fundamentals of Database ppt ch04
Fundamentals of Database ppt ch04Fundamentals of Database ppt ch04
Fundamentals of Database ppt ch04Jotham Gadot
 
Fundamentals of Database ppt ch02
Fundamentals of Database ppt ch02Fundamentals of Database ppt ch02
Fundamentals of Database ppt ch02Jotham Gadot
 
Fundamentals of Database ppt ch01
Fundamentals of Database ppt ch01Fundamentals of Database ppt ch01
Fundamentals of Database ppt ch01Jotham Gadot
 
Fundamentals of Database ppt ch03
Fundamentals of Database ppt ch03Fundamentals of Database ppt ch03
Fundamentals of Database ppt ch03Jotham Gadot
 
Opeating system programs
Opeating system programsOpeating system programs
Opeating system programsJotham Gadot
 

More from Jotham Gadot (11)

Research gadot
Research gadotResearch gadot
Research gadot
 
Auto cad manual
Auto cad manualAuto cad manual
Auto cad manual
 
Database using oracle 10g
Database using oracle 10gDatabase using oracle 10g
Database using oracle 10g
 
Case study 2
Case study 2Case study 2
Case study 2
 
C++ beginner's guide ch08
C++ beginner's guide ch08C++ beginner's guide ch08
C++ beginner's guide ch08
 
01 introduction-to-computers
01 introduction-to-computers01 introduction-to-computers
01 introduction-to-computers
 
Fundamentals of Database ppt ch04
Fundamentals of Database ppt ch04Fundamentals of Database ppt ch04
Fundamentals of Database ppt ch04
 
Fundamentals of Database ppt ch02
Fundamentals of Database ppt ch02Fundamentals of Database ppt ch02
Fundamentals of Database ppt ch02
 
Fundamentals of Database ppt ch01
Fundamentals of Database ppt ch01Fundamentals of Database ppt ch01
Fundamentals of Database ppt ch01
 
Fundamentals of Database ppt ch03
Fundamentals of Database ppt ch03Fundamentals of Database ppt ch03
Fundamentals of Database ppt ch03
 
Opeating system programs
Opeating system programsOpeating system programs
Opeating system programs
 

Recently uploaded

ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Victor Rentea
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data SciencePaolo Missier
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard37
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024Lorenzo Miniero
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewDianaGray10
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityWSO2
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch TuesdayIvanti
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....rightmanforbloodline
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxMarkSteadman7
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...SOFTTECHHUB
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...FIDO Alliance
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingScyllaDB
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxFIDO Alliance
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxFIDO Alliance
 

Recently uploaded (20)

Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Design and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data ScienceDesign and Development of a Provenance Capture Platform for Data Science
Design and Development of a Provenance Capture Platform for Data Science
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 
WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024WebRTC and SIP not just audio and video @ OpenSIPS 2024
WebRTC and SIP not just audio and video @ OpenSIPS 2024
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Platformless Horizons for Digital Adaptability
Platformless Horizons for Digital AdaptabilityPlatformless Horizons for Digital Adaptability
Platformless Horizons for Digital Adaptability
 
2024 May Patch Tuesday
2024 May Patch Tuesday2024 May Patch Tuesday
2024 May Patch Tuesday
 
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
TEST BANK For Principles of Anatomy and Physiology, 16th Edition by Gerard J....
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
The Ultimate Prompt Engineering Guide for Generative AI: Get the Most Out of ...
 
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...Hyatt driving innovation and exceptional customer experiences with FIDO passw...
Hyatt driving innovation and exceptional customer experiences with FIDO passw...
 
Event-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream ProcessingEvent-Driven Architecture Masterclass: Challenges in Stream Processing
Event-Driven Architecture Masterclass: Challenges in Stream Processing
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptxHarnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
Harnessing Passkeys in the Battle Against AI-Powered Cyber Threats.pptx
 
Introduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptxIntroduction to FIDO Authentication and Passkeys.pptx
Introduction to FIDO Authentication and Passkeys.pptx
 

Chap02

  • 1. Data Structures Using Java 1 Chapter 2 Inheritance and Exception Handling
  • 2. Data Structures Using Java 2 Chapter Objectives • Learn about inheritance • Learn about sub- and superclasses • Explore how to override the methods of a superclass • Examine how constructors of super- and subclasses work • Examine abstract classes • Learn about composition
  • 3. Data Structures Using Java 3 Chapter Objectives • Learn about exceptions • Become aware of exception classes and their hierarchy • Learn about checked and unchecked exceptions • Learn how to handle exceptions within a program • Examine try/catch blocks • Discover how to throw and rethrow an exception
  • 4. Data Structures Using Java 4 Inheritance • “is-a” relationship • Single inheritance – subclass derived from one existing class (superclass) • Multiple inheritance – Subclass derived from more than one superclass – Not supported by Java – In Java, a class can only extend definition of one class
  • 5. Data Structures Using Java 5 Inheritance
  • 6. Data Structures Using Java 6 Inheritance • Private members of superclass – private to superclass; cannot be accessed directly by subclass • Subclass can override method of superclass; redefinition applies only to object of subclass
  • 7. Data Structures Using Java 7 Inheritance • To write method definition of subclass to specify call to public method of superclass – If subclass overrides public method of superclass, to specify call to public method of superclass: super.MethodName(parameter list) – If subclass does not override public method of superclass, to specify call to public method of superclass: MethodName(parameter list)
  • 8. Data Structures Using Java 8 Defining Constructor of Subclass • Call to constructor of superclass – must be first statement – specified by: super parameter list
  • 9. Data Structures Using Java 9 The class Object • Directly or indirectly superclass of every class in Java • Public members of class Object can be overridden/invoked by object of any class type
  • 10. Data Structures Using Java 10 The class Object
  • 11. Data Structures Using Java 11 Objects of Superclasses and Subclasses • Cannot automatically make reference variable of subclass type point to object of superclass • Dynamic binding: method executed determined at execution time, not compile time • Operator instanceof : determines whether reference variable that points to object is of particular class type • ClassCastException thrown if class cast is not allowed
  • 12. Data Structures Using Java 12 The Operator instanceof • Reference of superclass type can point to objects of its subclass • Can determine if a reference variable points to an object using operator instanceof
  • 13. Data Structures Using Java 13 Abstract Methods and Classes • Abstract method: method that has only the heading with no body – must be declared abstract • Abstract class: class that is declared with the reserved word abstract in its heading
  • 14. Data Structures Using Java 14 Abstract Class • Can contain instance variables, constructors, finalizer, abstract and nonabstract methods • Cannot instantiate object of abstract class type; can only declare reference variable • Can instantiate object of subclass of abstract class, but only if subclass gives definitions of all abstract methods of superclass
  • 15. Data Structures Using Java 15 Composition • Another way to relate two classes • One or more members of a class are objects of another class type • “has-a” relation between classes
  • 16. Data Structures Using Java 16 Exception • Definition: an occurrence of an undesirable situation that can be detected during program execution • Examples – division by zero – trying to open an input file that does not exist is an exception – an array index that goes out of bounds
  • 17. Data Structures Using Java 17 Java Exception Hierarchy
  • 18. Data Structures Using Java 18 The class Throwable
  • 19. Data Structures Using Java 19 The class Exception and its Subclasses from java.lang
  • 20. Data Structures Using Java 20 The class Exception and its Subclasses from java.util
  • 21. Data Structures Using Java 21 The class Exception and its Subclasses from java.io
  • 22. Data Structures Using Java 22 Java’s Exception Class • Class Exception – Subclass of class Throwable – superclass of classes designed to handle exceptions • Various types of exceptions – I/O exceptions – Number format exceptions – File not found exceptions – Array index out of bounds exception • Various exceptions categorized into separate classes and contained in various packages
  • 23. Data Structures Using Java 23 The class Exception and its Constructors
  • 24. Data Structures Using Java 24 Java Exception Classes
  • 25. Data Structures Using Java 25 Exceptions Thrown by Methods
  • 26. Data Structures Using Java 26 Exceptions Thrown by Methods
  • 27. Data Structures Using Java 27 Checked Exceptions • Checked Exception: any exception that can be analyzed by the compiler • Example – IOExceptions
  • 28. Data Structures Using Java 28 Unchecked Exceptions • Unchecked Exception: exception that cannot be analyzed when the program compiles (must be checked for by programmer) • Examples – Division by zero – Array index out of hounds • Syntax – throws ExceptionType1, ExceptionType2, … *ExceptionType1, ExceptionType2, etc are names of exception classes
  • 29. Data Structures Using Java 29 Handling Exceptions within a Program • try/catch/finally block used to handle exceptions within a program • try block: – Includes statements that may generate an exception – Includes statements that should not be executed if an exception occurs – followed by zero or more catch blocks – May or may not be followed by finally block
  • 30. Data Structures Using Java 30 Handling Exceptions within a Program • Catch block: – heading specifies type of exception it can catch – contains exception handler; completely handles exception – can catch all exceptions of a specific type or all types of exceptions – may or may not be followed by a finally block • Finally block – Code contained in this block always executes – try block with no catch block has finally block
  • 31. Data Structures Using Java 31 Order of Catch Blocks • If exception in try block caught by first catch block, reaming catch blocks ignored • Must be careful about order catch blocks are listed
  • 32. Data Structures Using Java 32 Rethrowing and Throwing an Exception • Useful when – Catch block catches exception but is unable to handle it – Catch block decides exception should be handled by calling environment • Allows programmer to provide exception handling code in one place
  • 33. Data Structures Using Java 33 Exception Handling Techniques • Terminate program – Output appropriate error message upon termination • Fix error and continue – Repeatedly get user input/output appropriate error message until valid value is entered • Log error and continue – Write error messages to file and continue with program execution
  • 34. Data Structures Using Java 34 Creating Your Own Exception Classes • Exception class you define extends class Exception or one of its subclasses • Syntax to throw your own exception object – throw new ExceptionClassName(messageString);
  • 35. Data Structures Using Java 35 Programming Example: Grade Report • Main algorithm – Declare variables – Open input file – Open output file – Get number students registered and tuition rate – Load students’ data – Print grade reports
  • 36. Data Structures Using Java 36 Programming Example: Grade Report • Components: student, course • Operations on course – Set course information – Print course information – Show credit hours – Show course number – Show grade
  • 37. Data Structures Using Java 37 Programming Example: Grade Report • Operations on student – Set student information – Print student information – Calculate number of credit hours taken – Calculate GPA – Calculate billing amount – Sort the courses according to the course number
  • 38. Data Structures Using Java 38 Chapter Summary • Inheritance – Single and multiple – Rules and Uses – Superclasses/subclasses (objects) – Overriding/overloading methods • The class Object – Constructors – Rules • Abstract methods and classes
  • 39. Data Structures Using Java 39 Chapter Summary • Composition • Exception • Checked and Unchecked Exceptions • Creating your own exception classes • Exception handling techniques • Handling exceptions within a program