Chapter 9 Inheritance I. Scott MacKenzie 1 Outline 2 1
What is Inheritance? Like parent/child relationships in life In Java, all classes except Object are child classes A child class inherits the attributes (fields, methods) of its parent class A child class may use the fields and methods of a parent class as though they were defined in the child class itself A child class may itself have a child class (i.e., like parent/child/grandchild relationships in life) 3 Terminology A parent class is also called a superclass A child class is also called a subclass 4 2
Inheritance UML Diagrams (1) Parent class C is a P Child class 5 Inheritance UML Diagrams (2) Parent class Child class Parent class Child class 6 3
Inheritance UML Diagrams (3) 7 Method Section of API Methods defined in this class Methods defined in a parent class 8 4
Methods in a Child Class Methods in a child class are either... New Defined in the class itself, Inherited Defined in a parent class, Overriding Defined in a parent class, but re-defined ( overridden ) in the child class, or Overloading Defined in a parent class, but re-defined with a different signature ( overloaded ) in the child class 9 Child With Three Methods 10 5
RewardCard API 11 Inherited Fields 12 6
Fields in a Child Class Fields in a child class are either... New Defined in the class itself, Inherited Defined in a parent class, or Shadowed Defined in a parent class, but re-defined ( shadowed ) in the child class 13 Child With Two Fields 14 7
Fields in RewardCard Class 15 Inheritance Chains A class may be a subclass of another class, which in turn is a subclass of another class, and so on These are called inheritance chains A typical example is the JButton class in the javax.swing package... Last slide on Mar 8 View API for details 16 8
Polymorphism When using classes and subclasses, it is sometimes not known until runtime which subclass to use E.g., we might wish to create a credit card object without knowing whether it is an ordinary card or a rewards card That s OK. A RewardCard is a CreditCard, so the following makes sense CreditCard card = new RewardCard(123456, John Smith ); Furthermore, we can say that anywhere a CreditCard object is expected, a RewardCard object can be used This is called polymorphism (the ability of one thing to assume different forms) 17 instanceof operator (1) To determine if a CreditCard reference points to a RewardCard object, use Java s instanceof operator, for example... CreditCard card = new RewardCard(123456, John Smith ); IO.println(card instanceof RewardCard); outputs true 18 9
instanceof operator (2) What is the output? CreditCard joe = new RewardCard(123456, Joe Smith ); CreditCard sue = new CreditCard(234567, Sue Jones ); IO.println(joe instanceof RewardCard); IO.println(sue instanceof RewardCard); IO.println(joe instanceof CreditCard); IO.println(sue instanceof CreditCard); Answer: true false true true 19 import type.lang.*; import type.lib.*; instanceof operator (3) public class DemoInstanceof public static void main(string[] args) // ----------------------- // check for correct usage // ----------------------- if (args.length!= 1) IO.println("-------------------------------------------"); IO.println("Usage: java DemoInstanceof file\n"); IO.println("where 'file' is a credit card database file"); IO.println("(see 'creditcards2.txt' for example file)"); IO.println("-------------------------------------------"); System.exit(0); } // ----------------- // load the database // ----------------- IO.print("Loading the database... "); GlobalCredit gc = new GlobalCredit(); UniReader ur = new UniReader(args[0]); DemoInstanceof.java Demo 20 10
Manual Casts A reference of type sub can be promoted to type super without a cast: RewardCard rc = new RewardCard(123456, John Smith ); CreditCard cc = rc; A RewardCard is a CreditCard However, a reference of type super requires a cast to be demoted to type sub: CreditCard cc = new RewardCard(123456, John Smith ); RewardCard rc = (RewardCard)cc; A CreditCard is not necessarily a RewardCard, therefore a cast is necessary to demote cc 21 Manual Cast Gotchas Object casting (previous slide) affects only the compiler, not the actual object in memory This is different from casting among primitive types where casting a double to an int transforms the stored value While the cast may be allowed at compile time, the VM will generate a run-time error rate if the object is not of the type specified by the cast (avoided by using the instanceof operator before casting) 22 11
Reference Resolution and Binding Promotion allows a reference to point to either the superclass or the subclass If a feature (field, method) is used with the reference, is it the superclass or subclass feature that is used? Determining which requires reference resolution Two possibilities Early binding determined at compile-time (p. 250) Late binding determined at runtime (p. 251) 23 Early and Late Binding Early binding: Correct choices are made at compile time, re the appropriate fields and methods to use with card. Late binding: At runtime, the appropriate charge method is used, as per the reference type of card. This is an example of polymorphic behaviour. 24 12
Reference Resolution 25 Abstract Classes An abstract class is a class that is not fully implemented All the methods are defined, but some are not implemented. Abstract classes cannot be instantiated; however, there may be a service available to get an instance of an abstract class. An example is the Toolkit class in the java.awt package (next slide) 26 13
import type.lang.*; import java.awt.*; Abstract Classes (2) public class DemoToolkit public static void main(string[] args) // Toolkit is an 'abstract' class, so it cannot // be instantiated. That's too bad, because there // are some useful methods available in // Tooklit (see API). One of the methods, // 'getdefaulttooklit', is static and it returns // an instance of Toolkit. This is possible because // the implementation is provided with the Java SDK, // and it 'knows about' the target system. // Let's get it an instance of Toolkit. Toolkit t = Toolkit.getDefaultToolkit(); // Now that we have an instance of Toolkit, we can // do a variety of system-dependent things. Let's // see what the size of the screen is on the // target system. Dimension d = t.getscreensize(); // Print the screen size. IO.println(d); } } DemoToolkit.java Demo 27 Abstract Classes (3) Another example is the Calendar class in the java.util package (see API) GregorianCalendar, implements the methods in Calendar, as appropriate for parts of the world that use Gregorian calendars (see API) GregorianCalendar is defined to extends Calendar ; I.e., it is a subclass of Calendar and it implements the abstract methods in Calendar. GregorianCalendar can be instantiated, even though Calendar cannot (see next slide) 28 14
import type.lang.*; import java.util.*; Abstract Classes (4) public class DemoCalendar public static void main(string[] args) // GregorianCalendar 'extends' the abstract // class Calendar; i.e., it implements the // abstract methods in Calendar (and adds // a few of its own). Get an instance.. Calendar c = new GregorianCalendar(); } } //...and do something with it. Date d = c.gettime(); IO.println(d); DemoCalendar.java Demo 29 Interfaces An interface is similar to an abstract class The main difference is that an abstract class is realized by a subclass that extends the abstract class, whereas an interface is realized by any class that implements the interface An class can implement many interfaces, but a class can be a subclass to only one class An example is the Shape interface, and the Rectangle class that implements Shape (see API) 30 15
import type.lang.*; import java.awt.*; Interfaces (2) public class DemoRectangle public static void main(string[] args) IO.println("Input rectangle position (x,y coordinate of top-left corner):"); IO.print("x: "); int x = IO.readInt(); IO.print("y: "); int y = IO.readInt(); IO.println("\nInput rectangle size (width and height):"); IO.print("width: "); int w = IO.readInt(); IO.print("height: "); int h = IO.readInt(); Rectangle r = new Rectangle(x, y, w, h); while (true) IO.println("\nGive me a test point (or -1 to quit):"); IO.print("x: "); int testx = IO.readInt(); if (testx == -1) DemoRectangle.java Demo 31 Disparate Hierarchies Not in Java! 32 16
Object class 33 Object Class Methods Class getclass() boolean equals(object other) String to String() See API 34 17
Thank You 35 18