Class Hierarchy (Inheritance)

Slides:



Advertisements
Similar presentations
Module 8 “Polymorphism and Inheritance”. Outline Understanding Inheritance Inheritance Diagrams Constructors in Derived Classes Type Compatibility Polymorphism.
Advertisements

EXCEPTIONS. What’s an exception?? Change the flow of control when something important happens ideally - we catch errors at compile time doesn’t happen.
1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Chapter 8 Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
CS 211 Inheritance AAA.
Chapter 8 Inheritance 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design © 2007 Pearson Addison-Wesley. All rights reserved.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance Polymorphism Briana B. Morrison CSE 1302C Spring 2010.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Inheritance. 2 Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass.
INF 523Q Chapter 7: Inheritance. 2 Inheritance  Another fundamental object-oriented technique is called inheritance, which enhances software design and.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Chapter 7 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Chapter Day 21. © 2007 Pearson Addison-Wesley. All rights reserved7-2 Agenda Day 20 Problem set 4 Posted  10 problems from chapters 7 & 8  Due Nov 21.
Chapter 8 Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
Vocabulary Key Terms polymorphism - Selecting a method among many methods that have the same name. subclass - A class that inherits variables and methods.
Inheritance. © 2004 Pearson Addison-Wesley. All rights reserved 8-2 Inheritance Inheritance is a fundamental object-oriented design technique used to.
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
© 2004 Pearson Addison-Wesley. All rights reserved8-1 Chapter 8 : Inheritance Intermediate Java Programming Summer 2007.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
Chapter 12 Inheritance and Exceptions Lecture Slides to Accompany An Introduction to Computer Science Using Java (2nd Edition) by S.N. Kamin, D. Mickunas,
What is inheritance? It is the ability to create a new class from an existing class.
CSE 501N Fall ‘09 14: Inheritance 20 October 2009 Nick Leidenfrost.
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved2/23 Outline Creating Subclasses Overriding Methods Class Hierarchies.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
COS 312 DAY 13 Tony Gauvin. Ch 1 -2 Agenda Questions? First Progress Over due – Next progress report is March 26 Assignment 4 Posted – Chap 6 & 7 – Due.
Outline Creating Subclasses Overriding Methods Class Hierarchies Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright ©
Chapter 8 Inheritance Part 1. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Inheritance Inheritance is a fundamental object-oriented design technique.
Copyright © 2012 Pearson Education, Inc. Chapter 9 Inheritance Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
8. Inheritance “Is-a” Relationship. Topics Creating Subclasses Overriding Methods Class Hierarchies Abstract Class Inheritance and GUIs The Timer Class.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Inheritance. Inheritance is a fundamental object-oriented design technique used to create and organize reusable classes Chapter 8 focuses on: deriving.
Inheritance Inheritance allows a programmer to derive a new class from an existing one The existing class is called the super class, or parent class,
Inheritance Objectives: Creating new classes from existing classes The protected modifier Creating class hierarchies Abstract classes Indirect visibility.
Chapter 8 Specialization aka Inheritance. 2 Inheritance  Review of class relationships  Uses – One class uses the services of another class, either.
Chapter 8 Inheritance. 2  Review of class relationships  Uses – One class uses the services of another class, either by making objects of that class.
1 Inheritance  Inheritance allows a software developer to derive a new class from an existing one  The existing class is called the parent class, or.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Inheritance in Java. Access Specifiers private keywordprivate keyword –Used for most instance variables –private variables and methods are accessible.
November 27, 2001Lecture 231  Previous Lecture: Parameter passing Method overloading  Today’s Lecture: Introduction to inheritance Class diagrams and.
Java Software Solutions Lewis and Loftus Chapter 8 Copyright 1997 by John Lewis and William Loftus. All rights reserved. 1 Inheritance -- Introduction.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
© 2004 Pearson Addison-Wesley. All rights reserved April 10, 2006 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, SPRING.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Inheritance Chapter 8 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
© 2004 Pearson Addison-Wesley. All rights reserved November 14, 2007 Inheritance (part 2) ComS 207: Programming I (in Java) Iowa State University, FALL.
Lecture 12 Inheritance.
Chapter 8 Inheritance.
03/10/14 Inheritance-2.
Inheritance Inheritance allows a programmer to derive a new class from an existing one The existing class is called the super class, or parent class,
03/10/14 Chapter 9 Inheritance.
The super Reference Constructors cannot be used in child classes, even though they have public visibility Yet we often want to use the parent's constructor.
Java Programming Language
Overriding Methods & Class Hierarchies
Chapter 8 Inheritance Part 2.
Java Exception Dept. Business Computing University of Winnipeg
Programming in C# CHAPTER 5 & 6
Presentation transcript:

Class Hierarchy (Inheritance)

Inheritance Methods allows a software developer to reuse a sequence of statements Inheritance allows a software developer to reuse classes by deriving a new class from an existing one The existing class is called the parent class, or superclass, or base class The derived class is called the child class or subclass. As the name implies, the child inherits characteristics of the parent That is, the child class inherits the methods and data defined for the parent class

Inheritance Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class Animal weight : int + getWeight() : int Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent Bird + fly() : void

Deriving Subclasses In Java, we use the reserved word extends to establish an inheritance relationship class Animal { // class contents int weight; public void int getWeight() {…} } class Bird extends Animal public void fly() {…};

Class Hierarchy A child class of one parent can be the parent of another child, forming class hierarchies Animal Reptile Bird Mammal Snake Lizard Parrot Horse Bat At the top of the hierarchy there’s a default class called Object.

Class Hierarchy Good class design puts all common features as high in the hierarchy as reasonable inheritance is transitive An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an instance of class Object The class hierarchy determines how methods are executed: Previously, we took the simplified view that when variable v is an instance of class C, then a procedure call v.proc1() invokes the method proc1() defined in class C However, if C is a child of some superclass C’ (and hence v is both an instance of C and an instance of C’), the picture becomes more complex, because methods of class C can override the methods of class C’ (next two slides).

Defining Methods in the Child Class: Overriding by Replacement A child class can override the definition of an inherited method in favor of its own that is, a child can redefine a method that it inherits from its parent the new method must have the same signature as the parent's method, but can have different code in the body In java, all methods except of constructors override the methods of their ancestor class by replacement. E.g.: the Animal class has method eat() the Bird class has method eat() and Bird extends Animal variable b is of class Bird, i.e. Bird b = … b.eat() simply invokes the eat() method of the Bird class If a method is declared with the final modifier, it cannot be overridden

Defining Methods in the Child Class: Overriding by Refinement Constructors in a subclass override the definition of an inherited constructor method by refining them (instead of replacing them) Assume class Animal has constructors Animal(), Animal(int weight), Animal(int weight, int livespan) Assume class Bird which extends Animal has constructors Bird(), Bird(int weight), Bird(int weight, int livespan) Let’s say we create a Bird object, e.g. Bird b = Bird(5) This will invoke first the constructor of the Animal (the superclass of Bird) and then the constructor of the Bird This is called constructor chaining: If class C0 extends C1 and C1 extends C2 and … Cn-1 extends Cn = Object then when creating an instance of object C0 first constructor of Cn is invoked, then constructors of Cn-1, …, C2, C1, and finally the constructor of C The constructors (in each case) are chosen by their signature, e.g. (), (int), etc… If no constructor with matching signature is found in any of the class Ci for i>0 then the default constructor is executed for that class If no constructor with matching signature is found in the class C0 then this causes a compiler errorFirst the new method must have the same signature as the parent's method, but can have different code in the body

Recap: Class Hierarchy In Java, a class can extend a single other class (If none is stated then it implicitly extends an Object class) Animal Reptile Bird Mammal Snake Lizard Parrot Horse Bat Imagine what would happen to method handling rules if every class could extend two others… (Answer: It would create multiple problems!)

Overloading vs. Overriding Overloading deals with multiple methods in the same class with the same name but different signatures Overloading lets you define a similar operation in different ways for different data Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature Overriding lets you define a similar operation in different ways for different object types

Controlling Inheritance Visibility modifiers determine which class members are accessible and which do not Members (variables and methods) declared with public visibility are accessible, and those with private visibility are not Problem: How to make class/instance variables visible only to its subclasses? Solution: Java provides a third visibility modifier that helps in inheritance situations: protected

The protected Modifier The protected visibility modifier allows a member of a base class to be accessed in the child protected visibility provides more encapsulation than public does protected visibility is not as tightly encapsulated as private visibility Book protected int pages + getPages() : int + setPages(): void All these methods can access the pages instance variable. Note that by constructor chaining rules, pages is an instance variable of every object of class Dictionary. Dictionary + getDefinitions() : int + setDefinitions(): void + computeRatios() : double

Object Class

The Object Class A class called Object is defined in the java.lang package of the Java standard class library All classes are derived from the Object class even if a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class the Object class is therefore the ultimate root of all class hierarchies The Object class contains a few useful methods, which are inherited by all classes toString() equals() clone()

The Object Class: the toString Method That’s why the println method can call toString for any object that is passed to it – all objects are guaranteed to have a toString method via inheritance The toString method in the Object class is defined to return a string that contains the name of the object’s class and a hash value Every time we have defined toString, we have actually been overriding it

The Object Class: the equals Method The equals method of the Object class determines if two variables point to the same object (more shortly) Many classes (which all implicitly extend an Object class) override equals to define equality in some other way, e.g. Integer.equals looks at the represented integer, etc.

Exception Handling

Exceptions An exception is an object that enables a program to handle unusual/erroneous situations A method can throw an exception, e.g. [public/private] [static] void doubleArray( int[] A) throws Exception { … if (Index >= A.length) throw new Exception( “array too small ” + Index) } Class ArrayRangeException must be a subclass of (predefined) class Exception, and one of its constructors takes a string argument

Exeption is a class, and all Exception-like objects should be subclasses of Exception Throwable Exception Error RunTimeException LinkageError ArithmeticException IndexOutOfBoundsException ThreadDeath StringIndexOutOfBoundsException IllegalArguementException VirtualMachineError NumberFormatException IllegalAccessException AWTError NoSuchMethodException ClassNotFoundException

Extending Exception Classes A method can throw several exceptions (each of which is a subclass of the Exception class), e.g.: [public/private] [static] void scaleArray( int[] A, int s) throws ArrayRangeException, IllegalArgumentException { … if (Index >= A.length) throw new ArrayRangeException( “array too small ” + Index) … } Class ArrayRangeException must be a subclass of (predefined) class Exception, and one of its constructors takes a string argument Class IllegalArgumentException is predefined

Exception Propagation A (caller) method can deal with an exception thrown by the method it calls in 2 ways: A caller method can ignore exception handling In this case the exception thrown by the called method will be “passed up” and (effectively) thrown by the caller method This exception propagation will continue until the main method which was an access point of the java code, which will throw an error to the user (and print its description in the console output) Except if any of the methods along the caller/callee chain explicitly handles this exception. This breaks the chain of exception propagation, and after the exception is handled, the control returns to normal execution (see next slide).

Exception Handling: The try and catch Statement To handle an exception when it occurs, the line that throws the exception is executed within a try block A try block must be followed by one or more catch clauses, which contain code that processes an exception Each catch clause has an associated exception class, e.g. ArrayRangeException, IllegalArgumentException When an exception occurs, processing continues at the first catch clause that matches the (most specific) exception class of the exception object which is thrown by any statement in the try block.

Exception Handling: The try, catch Statement + finally try { Appointment last = calendar[max/scale] ; } catch (ArithmeticException ax) { System.out.println(“Division of “+max+” by “+scale+” cannot be carried out.”); } catch (ArrayIndexOutOfBoundsException aioobx) System.out.println(“The index “+index+” is out of bounds”); [ finally { <statement> } ]

The finally Clause A try statement can have an optional clause designated by the reserved word finally If no exception is generated, the statements in the finally clause are executed after the statements in the try block complete Also, if an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete