Class Hierarchy Inheritance Inheritance r Methods allows a

  • Slides: 24
Download presentation
Class Hierarchy (Inheritance)

Class Hierarchy (Inheritance)

Inheritance r Methods allows a software developer to reuse a r r r sequence

Inheritance r Methods allows a software developer to reuse a r r r 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 2

Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing

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

Deriving Subclasses r In Java, we use the reserved word extends to establish an

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

Class Hierarchy r A child class of one parent can be the parent of

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

Class Hierarchy r Good class design puts all common features as high in the

Class Hierarchy r Good class design puts all common features as high in the hierarchy as reasonable r inheritance is transitive m An instance of class Parrot is also an instance of Bird, an instance of Animal, …, and an instance of class Object r The class hierarchy determines how methods are executed: m m Previously, we took the simplified view that when variable v is an instance of class C, then a procedure call v. proc 1() invokes the method proc 1() 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). 6

Defining Methods in the Child Class: Overriding by Replacement r A child class can

Defining Methods in the Child Class: Overriding by Replacement r A child class can override the definition of an inherited method in favor of its own m m 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 r In java, all methods except of constructors override the methods of their ancestor class by replacement. E. g. : m m 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 r If a method is declared with the final modifier, it cannot be overridden 7

Defining Methods in the Child Class: Overriding by Refinement r Constructors in a subclass

Defining Methods in the Child Class: Overriding by Refinement r 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, int livespan) - Assume class Bird which extends Animal has constructors Bird(), 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 r This is called constructor chaining: If class C 0 extends C 1 and C 1 extends C 2 and … Cn-1 extends Cn = Object then when creating an instance of object C 0 first constructor of Cn is invoked, then constructors of Cn-1, …, C 2, C 1, 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 C 0 then this causes a compiler error. First the new method must have the same signature as the parent's method, but can have different code in the body 8

Recap: Class Hierarchy r In Java, a class can extend a single other class

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

Overloading vs. Overriding r Overloading deals with r Overriding deals with r Overloading lets

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

Controlling Inheritance r Visibility modifiers determine which class members are accessible and which do

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

The protected Modifier r The protected visibility modifier allows a member of a base

The protected Modifier r The protected visibility modifier allows a member of a base class to be accessed in the child m m protected visibility provides more encapsulation than public does protected visibility is not as tightly encapsulated as private visibility 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. Book protected int pages + get. Pages() : int + set. Pages(): void Dictionary + get. Definitions() : int + set. Definitions(): void + compute. Ratios() : double 12

Object Class

Object Class

The Object Class r A class called Object is defined in the java. lang

The Object Class r A class called Object is defined in the java. lang package of the Java standard class library r All classes are derived from the Object class m m 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 is therefore the ultimate root of all class hierarchies r The Object class contains a few useful methods, which are inherited by all classes m m m to. String() equals() clone() 14

The Object Class: the to. String Method r That’s why the println method can

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

The Object Class: the equals Method r The equals method of the Object class

The Object Class: the equals Method r The equals method of the Object class determines if two variables point to the same object (more shortly) r 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. 16

Exception Handling

Exception Handling

Exceptions r An exception is an object that enables a program to handle unusual/erroneous

Exceptions r 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 double. Array( int[] A) throws Exception { … if (Index >= A. length) throw new Exception( “array too small ” + Index) … } m r Class Array. Range. Exception must be a subclass of (predefined) class Exception, and one of its constructors takes a string argument 18

Exeption is a class, and all Exception-like objects should be subclasses of Exception Object

Exeption is a class, and all Exception-like objects should be subclasses of Exception Object Throwable Exception Error Run. Time. Exception Linkage. Error Arithmetic. Exception Index. Out. Of. Bounds. Exception Thread. Death String. Index. Out. Of. Bounds. Exception Illegal. Arguement. Exception Virtual. Machine. Error Number. Format. Exception Illegal. Access. Exception AWTError No. Such. Method. Exception Class. Not. Found. Exception 19

Extending Exception Classes r A method can throw several exceptions (each of which is

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

Exception Propagation A (caller) method can deal with an exception thrown by the method

Exception Propagation A (caller) method can deal with an exception thrown by the method it calls in 2 ways: r A caller method can ignore exception handling m In this case the exception thrown by the called method will be “passed up” and (effectively) thrown by the caller method m 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) m 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). 21

Exception Handling: The try and catch Statement r To handle an exception when it

Exception Handling: The try and catch Statement r To handle an exception when it occurs, the line that throws the exception is executed within a try block r A try block must be followed by one or more catch clauses, which contain code that processes an exception r Each catch clause has an associated exception class, e. g. Array. Range. Exception, Illegal. Argument. Exception r 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. 22

Exception Handling: The try, catch Statement + finally try { Appointment last = calendar[max/scale]

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

The finally Clause r A try statement can have an optional clause designated by

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