Understanding Inheritance and Interfaces

Similar documents
Chapter 5 Object-Oriented Programming

Implementing Association Relationships

Microsoft Visual Basic 2005: Reloaded

Java Object Oriented Design. CSC207 Fall 2014

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

Chapter 2. Building Multitier Programs with Classes The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Polymorphism and Inheritance

Programming II (CS300)

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

IT101. Inheritance, Encapsulation, Polymorphism and Constructors

Programming II (CS300)

Chapter 12. OOP: Creating Object- Oriented Programs. McGraw-Hill. Copyright 2011 by The McGraw-Hill Companies, Inc. All Rights Reserved.

Inheritance, Polymorphism, and Interfaces

CS-202 Introduction to Object Oriented Programming

Data Structures (list, dictionary, tuples, sets, strings)

8. Polymorphism and Inheritance

Object Oriented Programming. Java-Lecture 11 Polymorphism

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

Computer Science 4U Unit 1. Programming Concepts and Skills Modular Design

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

Chapter 14 Abstract Classes and Interfaces

Chapter 10 Classes Continued. Fundamentals of Java

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE

Inheritance (Outsource: )

Software Development. Modular Design and Algorithm Analysis

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

PROGRAMMING LANGUAGE 2

The Essence of Object Oriented Programming with Java and UML. Chapter 2. The Essence of Objects. What Is an Object-Oriented System?

Lecture 2: Java & Javadoc

Polymorphism. return a.doublevalue() + b.doublevalue();

Inheritance and Polymorphism

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

JAVA MOCK TEST JAVA MOCK TEST II

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Inheritance -- Introduction

CS260 Intro to Java & Android 03.Java Language Basics

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

CLASSES AND OBJECTS IN JAVA

Chapter 02 Building Multitier Programs with Classes

More on Objects in JAVA TM

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

ITI Introduction to Computing II

Big software. code reuse: The practice of writing program code once and using it in many contexts.

C++ Important Questions with Answers

Building Multitier Programs with Classes

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Object Oriented Programming in C#

CS 251 Intermediate Programming Inheritance

ITI Introduction to Computing II

(12-1) OOP: Polymorphism in C++ D & D Chapter 12. Instructor - Andrew S. O Fallon CptS 122 (April 3, 2019) Washington State University

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Index. Index. More information. block statements 66 y 107 Boolean 107 break 55, 68 built-in types 107

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

ECE 122. Engineering Problem Solving with Java

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

VIRTUAL FUNCTIONS Chapter 10

How to be a Good Bean

Introduction to Object-Oriented Programming

Motivations. Objectives. object cannot be created from abstract class. abstract method in abstract class

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Object Oriented Programming in Java. Jaanus Pöial, PhD Tallinn, Estonia

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

CS111: PROGRAMMING LANGUAGE II

CSCE3193: Programming Paradigms

Programming Exercise 14: Inheritance and Polymorphism

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Chapter 4 Defining Classes I

Object-Oriented Design

Inheritance CSC 123 Fall 2018 Howard Rosenthal

CS1150 Principles of Computer Science Objects and Classes

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

8.1 Inheritance. 8.1 Class Diagram for Words. 8.1 Words.java. 8.1 Book.java 1/24/14

Object Oriented Programming

CS200: Advanced OO in Java

Boaz Kantor Introduction to Computer Science IDC Herzliya ( Reichman )

INTERFACES. 24-Dec-10 INTERFACES VS. INHERITANCE. Boaz Kantor Introduction to Computer Science IDC Herzliya ( Reichman ) Interfaces: Inheritance:

CMSC 132: Object-Oriented Programming II

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

25. Generic Programming

Inheritance and Encapsulation. Amit Gupta

Polymorphism. Arizona State University 1

Motivations. Chapter 13 Abstract Classes and Interfaces

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

COP 3330 Final Exam Review

Object Oriented Programming

Java Fundamentals (II)

Chapter 6 Introduction to Defining Classes

The major elements of the object-oriented model

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

[ L5P1] Object-Oriented Programming: Advanced Concepts

CS608 Lecture Notes. Visual Basic.NET Programming. Object-Oriented Programming Inheritance (Part II) (Part II of II) (Lecture Notes 3B)

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

Topic 7: Inheritance. Reading: JBD Sections CMPS 12A Winter 2009 UCSC

Classes. Classes. Classes. Class Circle with methods. Class Circle with fields. Classes and Objects in Java. Introduce to classes and objects in Java.

Transcription:

Chapter 8 Objectives Understanding Inheritance and Interfaces In this chapter, you will: Implement the Boat generalization/specialization class hierarchy Understand abstract and final classes and the MustInherit and NotInheritable keywords Override a superclass method Understand private versus protected access 1 2 Objectives In this chapter, you will: Explore the Lease subclasses and abstract methods Understand and use interfaces Use custom exceptions Understand the Object class and inheritance Implementing the Boat Generalization/Specification Hierarchy Boat class Stores information about a boat s State registration number Length Manufacturer Model year 3 4 Implementing the Boat Generalization/Specification Hierarchy Boat class Parameterized constructor Accepts values for all four attributes Eight standard accessor methods Four setter methods Four getter methods TellAboutSelf method Testing the Boat Superclass with a Windows Form A Windows application and a Windows form with buttons can be used to test all problem domain classes Windows form testers Accomplish the same objective as a class module To systematically test each problem domain class to demonstrate that all functionality works as intended 5 6

Generalization/specialization hierarchy Superclass Includes attributes and methods that are common to specialized subclasses Instances of the subclasses Inherit attributes and methods of the superclass Include additional attributes and methods Superclass Boat class Four attributes and eight accessor methods Subclasses Sailboat Three additional attributes Powerboat Two additional attributes 7 8 Inherits keyword Used in the class header to implement a subclass Indicates which class the new class is extending Example: Class header to define the Sailboat class as a subclass of Boat: Public Class Sailboat Inherits Boat 9 10 Class definition of a subclass Includes any attributes and methods in addition to those inherited from the superclass Sailboat constructor Accepts seven parameters Four for attributes defined in the Boat superclass Three for additional attributes defined in Sailboat Sailboat constructor MyBase.New call Used to set attributes for registration number, length, manufacturer, and year Invokes constructor of the superclass Must be the first statement in the constructor Required unless the superclass includes a default constructor without parameters Sailboat set accessor methods Used to set the three remaining attribute values 11 12

Adding a Second Subclass Powerboat Adding a Second Subclass Powerboat Powerboat class Extends the Boat class Declares two attributes: numberengines fueltype Constructor expects six parameters Four required by Boat Two additional attributes for Powerboat Once the boats are created Four getter methods inherited from Boat Can be invoked for both sailboats and powerboats Three additional getter methods of Sailboat Not present in powerboats Two additional getter methods of Powerboats Not present in sailboats 13 14 Understanding Abstract and Final Classes Using the MustInherit Keyword Concrete classes Classes that can be instantiated Examples Sailboat class Powerboat class Abstract class Not intended to be instantiated Only used to extend into subclasses Used to facilitate reuse MustInherit keyword Used in class header to declare an abstract class Example: Class header to make the Boat class abstract: Public MustInherit Class Boat 15 16 Using the NotInheritable Keyword Overriding a Superclass Method A Final class A class that cannot be extended Created for security purposes or efficiency Created using the NotInheritable keyword Example Class header for the Powerboat class : Method overriding Method in subclass will be invoked instead of method in the superclass if both methods have the same signature Allows the subclass to modify the behavior of the superclass Public NotInheritable Class Powerboat Inherits Boat 17 18

Overriding a Superclass Method Method overriding vs. method overloading Overloading Two or more methods in the same class have the same name but a different return type or parameter list Overriding Methods in both the superclass and subclass have the same signature Overriding the Boat TellAboutSelf Method TellAboutSelf method Demonstrates method overriding Used to make it easier to get information about an instance of the class Overridable keyword Included in method header to make a method overridable 19 20 Overriding the Boat TellAboutSelf Method To override the TellAboutSelf method Use the same method signature in the subclass, except for using Overrides keyword in place of Overridable keyword Once a method is overriden Statements in the subclass method control what system does when a sailboat instance is asked to tell about itself Method in Boat is ignored Overriding and Invoking a Superclass Method Sometimes the programmer needs to override a method by extending what the method does For example Powerboat TellAboutSelf method invokes the superclass method using MyBase keyword Superclass method name 21 22 Overriding, Polymorphism, and Dynamic Binding Understanding Private Versus Protected Access Polymorphism Objects of different classes can respond to the same message in their own way Dynamic binding Used to resolve which method to invoke when the system runs and finds more than one method with the same name Provides flexibility when adding new subclasses that override superclass methods Declaring attributes as private Done by using Private keyword No other object can directly read or modify the values Other objects must use methods of the class to get or set values Ensures encapsulation and information hiding Limits the ability of an instance of a subclass to directly access attributes defined by the superclass 23 24

Understanding Private Versus Protected Access Declaring attributes as Protected Done by using Protected keyword Values can be directly accessed by subclasses Local variable Accessible only to statements within a method where it is declared Exists only as long as the method is executing Does not need to be declared as private, protected, friend, or public Understanding Private Versus Protected Access Methods Private methods Can only be invoked from a method within the class Private methods Cannot be invoked even by subclass methods Protected methods Can be invoked by a method in a subclass 25 26 Introducing the Lease Subclasses and Abstract Methods Introducing the Lease Subclasses and Abstract Methods Lease class Subclasses AnnualLease DailyLease Attributes Amount: a numeric value Start date: a reference variable End date : a reference variable Defined as abstract Includes MustInherit keyword in header 27 28 Introducing the Lease Subclasses and Abstract Methods Lease class constructor Accepts one parameter A reference to a DateTime instance for start date of the lease Sets end date to Nothing Sets amount of the lease to zero Subclasses set end date and calculate amount depending on type of the lease Adding an Abstract Method to Lease Sometimes it is desirable to require all subclasses to include a method All Lease subclasses need a CalculateFee method Subclasses are responsible for determining what the lease amount will be Necessary for polymorphism 29 30

Adding an Abstract Method to Lease Abstract method A method without any statements that must be overridden by all subclasses Declared by using MustOverride keyword in method header For example CalculateFee method of the Lease class Implementing the AnnualLease Subclass AnnualLease subclass attributes balancedue The amount of the annual lease that remains unpaid paymonthly A Boolean Indicates whether monthly payments will be made for the annual lease 31 32 Implementing the AnnualLease Subclass If paymonthly is true balancedue is initially set to eleven-twelfths of the lease amount If paymonthly is false balancedue will be zero Implementing the DailyLease Subclass DailyLease A subclass of the Lease class Used when a customer leases a slip for a short time Additional attribute Number of days of the lease Calculated based on the start date and end date 33 34 Understanding and Using Interfaces Understanding and Using Interfaces An interface Defines abstract methods and constants that must be implemented by classes that use the interface Can be used to ensure that an instance has a defined set of methods Component-based development Components interact in a system using a welldefined interface Components might be built using a variety of technologies Interfaces Define how components can be used Play an important role in developing componentbased systems 35 36

Understanding and Using Interfaces Creating a Interface A class Can inherit from only one superclass Can implement one or more interfaces Interfaces allow subclasses a form of multiple inheritance Multiple inheritance Ability to inherit from more than one class A subclass is part of two or more generalization/specialization hierarchies Interface Name (by convention) Begins with a capital letter I Uses the word interface Header Uses Interface keyword, followed by the interface name Methods Include no code 37 38 Creating a Interface Implementing More Than One Interface A class can implement an interface by adding the following to the class header: Implements keyword Name of the interface To implement more than one interface Use Implements keyword in the class header Separate multiple interface names by commas For example: Public Class DailyLease Inherits Lease Implements ILeaseInterface, ICompanyInterface 39 40 Using Custom Exceptions Defining LeasePaymentException NotInheritable keyword Any class that is not declared NotInheritable can be extended Custom exception An exception written specifically for an application An example of extending a built-in class LeasePaymentException A custom exception Created by defining a class that extends the Exception class Designed for use by the AnnualLease class Thrown if payment is invalid 41 42

Throwing a Custom Exception RecordLeasePayment method A custom method Records a payment Expects to receive the amount of the payment Throws a LeasePaymentException instance if payment amount is not valid Understanding the Object Class and Inheritance Object class Extended by all classes in Defines basic functionality that other classes need in ToString method A method of the Object class Inherited by all classes By default, returns a string representation of the class name Overridden by other classes to provide more specific information 43 44 Understanding the Object Class and Inheritance Summary Some other methods of the Object class Equals GetHashCode GetType ReferenceEquals The Default New constructor Generalization/specialization hierarchies show superclasses and subclasses The subclass inherits attributes and methods of the superclass An abstract class: a class that is not instantiated; exists only to serve as a superclass A final class: a class that cannot be extended 45 46 Summary An abstract method in a superclass must be implemented by all the subclasses An interface can be used to require that classes contain specific methods Custom exceptions can provide detailed information following an exception In, the Object class is the superclass of all classes 47