Inheritance Polymorphism 1 Introduction Besides composition another form

Inheritance & Polymorphism 1

Introduction Besides composition, another form of reuse is inheritance. With inheritance, an object can inherit behavior from another object, thus reusing its code. The class inheriting is called a subclass (or derived class). The class inherited from is called a superclass (or base class). Inheritance & Polymorphism 2

Subclass A subclass usually adds to its superclass, thus creating a more specialized object. A subclass may be the superclass for its own subclass, thus creating a class hierarchy. The immediate superclass for a subclass is called its direct superclass. A superclass above the direct superclass is called an indirect superclass. In Java, the Object class is a direct or indirect superclass to all other classes. Inheritance & Polymorphism 3

Multiple Inheritance Java, unlike C++, does not support multiple inheritance (Java allows only one direct superclass). Java uses interfaces to provide some of this capability. With an interface, multiple classes can support some of the same behavior. Inheritance & Polymorphism 4

Inheritance Relationships Inheritance is known as an “is-a relationship”. Composition is a “has-a relationship”. A car is a vehicle. A car has a steering wheel. Inheritance & Polymorphism 5

Protected Members If a member is given the “protected” access modifier, then subclasses of that class may access it, as well as classes in the same package: Specifie Class r Subclass Package World Public x x x Protected x x x package x private x x x Inheritance & Polymorphism 6

Inheritance & Polymorphism Inheritance is a form of software reusability in which new classes are created from existing classes by n n absorbing their attributes and behaviours and enhance these, with capabilities the new classes require. Polymorphism n n enables us to write programs (and methods) in a general fashion to handle a wide variety of existing and yet-to-be-specified related classes. makes it easy to add new capabilities to a system. Inheritance and Polymorphism are effective techniques for dealing with software complexity. Inheritance & Polymorphism 7

Polymorphism means many forms. In object-oriented programming, a method of a superclass may be implemented in many different ways by its subclasses. Thus, a command may have many different forms. Polymorphism allows programs to similarly process different objects of the same superclass. Suppose for example a class animal has subclasses of fish, frog, and bird. The superclass defines a move method, but each specific animal may move in a different way. Inheritance & Polymorphism 8

Superclass defines move method Animal Fish Frog Bird Each subclass implements move method in its own way Programmer can send the “move” message to each object without regard to which object it is. Inheritance & Polymorphism 9

Polymorphism makes it possible to design and implement systems that are more easily extensible. Programs can be written to process generically – as superclass objects – objects of all existing classes in a hierarchy. Classes that do not exist during program development can be added with little or no modifications to the generic part of the program (as long as those classes are part of the hierarchy that is being processed generically). The only parts of a program that need modification are those parts that require direct knowledge of the particular class that is added to the hierarchy. We will look at two class hierarchies later on…. . Inheritance & Polymorphism 10

Polymorphism The next example illustrates inheritance and polymorphism. When the “to. String” method is called, Java performs dynamic binding (or late binding) which determines the method to call at runtime by examining which object is making the call, rather than at compile-time by only considering the reference type. Inheritance & Polymorphism 11

Point, Circle Example (1) public class Point { protected int x, y; // coordinates of the Point public Point() { set. Point( 0, 0 ); } public Point( int a, int b ) { set. Point( a, b ); } Inheritance & Polymorphism 12

Point, Circle Example (1 a) public void set. Point( int a, int b ) { x = a; y = b; } public int get. X() { return x; } public int get. Y() { return y; } public String to. String() { return "[" + x + ", " + y + "]"; } } Inheritance & Polymorphism 13

Point, Circle Example (2) public class Circle extends Point { // inherits from Point protected double radius; public Circle() { // implicit call to superclass constructor set. Radius( 0 ); } public Circle( double r, int a, int b ) { super( a, b ); // call to superclass constructor set. Radius( r ); } Inheritance & Polymorphism 14

Point, Circle Example (2 a) public void set. Radius( double r ) { radius = ( r >= 0. 0 ? r : 0. 0 ); } public double get. Radius() { return radius; } public double area() { return Math. PI * radius; } public String to. String() { return "Center = " + "[" + x + ", " + y + "]" + "; Radius = " + radius; } } Inheritance & Polymorphism 15

Point, Circle Example (3) import java. text. Decimal. Format; import javax. swing. JOption. Pane; public class Tester { public static void main( String args[] ) { Point point. Ref, p; Circle circle. Ref, c; String output; p = new Point( 30, 50 ); c = new Circle( 2. 7, 120, 89 ); output = "Point p: " + p. to. String() + "n. Circle c: " + c. to. String(); // use the "is a" relationship to refer to a Circle // with a Point reference point. Ref = c; // assign Circle to point. Ref Polymorphism & Dynamic Binding output += "nn. Circle c (via point. Ref): " + point. Ref. to. String(); Inheritance & Polymorphism 16

Point, Circle Example (4) // Use downcasting (casting a superclass reference to a subclass data type) to assign point. Ref to circle. Ref = (Circle) point. Ref; output += "nn. Circle c (via circle. Ref): " + circle. Ref. to. String(); Decimal. Format precision 2 = new Decimal. Format( "0. 00" ); output += "n. Area of c (via circle. Ref): " + precision 2. format( circle. Ref. area() ); // Attempt to refer to Point object with Circle reference if ( p instanceof Circle ) { circle. Ref = (Circle) p; output += "nncast successful"; } else output += "nnp does not refer to a Circle"; JOption. Pane. show. Message. Dialog( null, output, "Demonstrating the "is a" relationship", JOption. Pane. INFORMATION_MESSAGE ); System. exit( 0 ); } } Inheritance & Polymorphism 17

Point, Circle Example (5) Inheritance & Polymorphism 18

Case Study - Point, Circle, Cylinder Suppose a set of shape classes such as Circle, Triangle , Square etc. are all derived from superclass Shape, and each class has the ability to draw itself (has its own draw() method, which would be different in each case). When drawing a shape, whatever shape it might be, it would be nice to be able to treat all these shapes generically as objects of the superclass Shape. Then to draw any shape, we could call the draw() method of superclass Shape and let the program determine dynamically (at run time) which subclass draw() method should be called (depending on the objects type). To enable this kind of behaviour, we declare draw() in the superclass, and override draw() in each of the subclasses to draw the appropriate shape. Inheritance & Polymorphism 19

abstract An abstract method is not actually implemented in the class. The body of the method is implemented in subclasses of that class. public abstract void draw(); An abstract method must be part of an abstract class. public abstract class Shape extends Object Abstract classes cannot be instantiated. It is a compile-time error to try something like Shape m = new Shape(); where Shape has been declared to be abstract Inheritance & Polymorphism 20

Abstract Classes A variable of an abstract type can refer to an object of a subclass of that type. This permits polymorphism. Sometimes a collection, such as an array, of a superclass or abstract superclass type contains objects of subclasses. An iterator is used to traverse all objects in the collection. A message sent to each object behaves in a polymorphic manner. Inheritance & Polymorphism 21

Case Study : Point, Circle, Cylinder (1) public abstract class Shape extends Object { public double area() {return 0. 0; } public double volume() {return 0. 0; } public abstract String get. Name(); public abstract void Draw(); } Inheritance & Polymorphism 22

Case Study : Point, Circle, Cylinder (2) import javax. swing. JOption. Pane; public class Point extends Shape { protected int x, y; // coordinates of the Point public Point(){ set. Point( 0, 0 ); } public Point( int a, int b ){ set. Point( a, b ); } public void set. Point( int a, int b ) { x = a; y = b; } Inheritance & Polymorphism 23

Case Study : Point, Circle, Cylinder (3) public int get. X() { return x; } public int get. Y() { return y; } public String to. String() { return "[" + x + ", " + y + "]"; } public String get. Name(){ return "Point"; } public void Draw() { JOption. Pane. show. Message. Dialog(null, get. Name() + ": " + this); } } Inheritance & Polymorphism 24

Case Study : Point, Circle, Cylinder (4) import javax. swing. JOption. Pane; public class Circle extends Point { protected double radius; // inherits from Point public Circle(){ // implicit call to superclass constructor set. Radius( 0 ); } public Circle( double r, int a, int b ){ super( a, b ); // call to superclass constructor set. Radius( r ); } public void set. Radius( double r ) { radius = ( r >= 0. 0 ? r : 0. 0 ); } Inheritance & Polymorphism 25

Case Study : Point, Circle, Cylinder (5) public double get. Radius() { return radius; } public double area() { return Math. PI * radius; } public String to. String() { return "Center = " + "[" + x + ", " + y + "]" + "; Radius = " + radius; } public String get. Name() { return "Circle"; } public void Draw() { JOption. Pane. show. Message. Dialog(null, get. Name() + ": " + this); } } Inheritance & Polymorphism 26

Case Study : Point, Circle, Cylinder (6) import javax. swing. JOption. Pane; public class Cylinder extends Circle { protected double height; // height of Cylinder // no-argument constructor public Cylinder() { // implicit call to superclass constructor here set. Height( 0 ); } // constructor public Cylinder( double h, double r, int a, int b ) { super( r, a, b ); // call superclass constructor set. Height( h ); Inheritance & Polymorphism } 27

Case Study : Point, Circle, Cylinder (7) // Set height of Cylinder public void set. Height( double h ) { height = ( h >= 0 ? h : 0 ); } // Get height of Cylinder public double get. Height() { return height; } // Calculate area of Cylinder (i. e. , surface area) public double area() { return 2 * super. area() + 2 * Math. PI * radius * height; } Inheritance & Polymorphism 28

Case Study : Point, Circle, Cylinder (8) // Calculate volume of Cylinder public double volume() { return super. area() * height; } // Convert a Cylinder to a String public String to. String() { return super. to. String() + "; Height = " + height; } // Return the class name public String get. Name() { return "Cylinder"; } public void Draw() { JOption. Pane. show. Message. Dialog(null, get. Name() + ": " + this); } } Inheritance & Polymorphism 29

Case Study : Point, Circle, Cylinder (9) import java. text. Decimal. Format; import javax. swing. JOption. Pane; public class Tester { public static void main( String args[] ) { String output; Point point = new Point( 7, 11 ); Circle circle = new Circle( 3. 5, 22, 8 ); Cylinder cylinder = new Cylinder( 10, 3. 3, 10 ); Shape array. Of. Shapes[]; array. Of. Shapes = new Shape[ 3 ]; Inheritance & Polymorphism 30
![Case Study : Point, Circle, Cylinder (10) // aim array. Of. Shapes[0] at subclass Case Study : Point, Circle, Cylinder (10) // aim array. Of. Shapes[0] at subclass](http://slidetodoc.com/presentation_image_h2/639064c9a635212dac7c0fd4e82e3c49/image-31.jpg)
Case Study : Point, Circle, Cylinder (10) // aim array. Of. Shapes[0] at subclass Point object array. Of. Shapes[ 0 ] = point; // aim array. Of. Shapes[1] at subclass Circle object array. Of. Shapes[ 1 ] = circle; // aim array. Of. Shapes[2] at subclass Cylinder object array. Of. Shapes[ 2 ] = cylinder; point. Draw(); circle. Draw(); cylinder. Draw(); Decimal. Format precision 2 = new Decimal. Format( "0. 00" ); Inheritance & Polymorphism 31

Case Study : Point, Circle, Cylinder (11) // Loop through array. Of. Shapes and print the name, // area, and volume of each object. for ( int i = 0; i < array. Of. Shapes. length; i++ ) { Polymorphism & array. Of. Shapes[ i ]. Draw(); Dynamic Binding output = "n. Area = " + precision 2. format( array. Of. Shapes[ i ]. area() ) + "n. Volume = " + precision 2. format( array. Of. Shapes[ i ]. volume() ); JOption. Pane. show. Message. Dialog( null, output, "Demonstrating Polymorphism", JOption. Pane. INFORMATION_MESSAGE ); } System. exit( 0 ); } } Inheritance & Polymorphism 32

Case Study : Notes (12) Superclass Shape extends Object and consists of 3 public methods and contains no data (although it could). n n get. Name() & Draw() are abstract so they are overridden in each of the subclasses area() & volume() are overridden in subclasses when it is appropriate for those classes to have a different area/volume calculation Class Point is derived from Shape. n n area() & volume() are inherited (not overridden) from Shape get. Name() & Draw() are implementations of the abstract methods in the superclass. If either of these methods were not defined, class Point would itself be an abstract class. Inheritance & Polymorphism 33

Case Study : Notes (13) Class Circle is derived from Point n n area() is overridden as the area is different to that of a Point & volume() is inherited because a Circle has no volume get. Name() & Draw() are implementations of the abstract methods in the superclass. If either of these methods were not defined here, the Point version of these methods would be inherited. Class Cylinder is derived from Circle n n area() is overridden as the area is different to that of a Circle & volume() is overridden because a Cylinder has a volume get. Name() & Draw() are implementations of the abstract methods in the superclass. If either of these methods were not defined here, the Circle version of these methods would be inherited. In each class new methods are added specific to that class Inheritance & Polymorphism 34

Interfaces (1) Interfaces provide some features of multiple inheritance: Like an abstract class, an interface defines a set of methods (and perhaps constants as well), but no implementation. n By using the implements keyword, a class can indicate that it implements that set of methods. n This makes it unnecessary for related classes to share a common superclass or to directly subclass object. n It’s possible for a class to implement several interfaces. n Inheritance & Polymorphism 35

Interfaces (3) An interface is like a class with nothing but abstract methods and final, static fields. All methods and fields of an interface must be public. However, unlike a class, an interface can be added to a class that is already a subclass of another class. Furthermore an interface can apply to members of many different classes When you introduce a new class, you can choose to “support” any number of interfaces For each interface you support you must implement member functions defined in the interface Inheritance & Polymorphism 36

Final If a method is declared “final”, it cannot be overridden in a subclass. All subclass calls to a final method would call the superclass method. Therefore, this binding can be done at compile time rather than runtime. This permits inlining to be performed by the compiler for simple methods. Inheritance & Polymorphism 37

Final If a class is declared final, it cannot be subclassed. One reason for doing this is for security purposes. For example, the “String” class in Java is final, so that it cannot be subclassed such that its security features are bypassed. Inheritance & Polymorphism 38

Interfaces Sometimes different classes need common functionality. Such cases are supported by creating an “interface”. An interface specifies a set of methods to support but does not provide implementation. Interfaces only contain constants and abstract methods. Inheritance & Polymorphism 39

Interfaces All interface members are public. Methods are abstract. Constants are static and final. Generally, the keywords public, abstract, static and final are not used in an interface declaration since they will have these characteristics by default. Inheritance & Polymorphism 40

Interfaces To use an interface, a class “implements” the interface. Each interface method must be declared in the (concrete) class that implements the interface using the same signature. Using interfaces lets very different objects behave in a polymorphic way. Inheritance & Polymorphism 41

Interfaces A class can inherit from only one direct superclass, but it can implement multiple interfaces. public class My. Class extends My. Super implements IFace 1, IFace 2, IFace 3, … An interface can be used when there is no implementation to inherit. If a class implements an interface but not all of its methods, it must be an abstract class. Interface methods are implicitly abstract. Interfaces are defined in their own. java file named with the interface name. Inheritance & Polymorphism 42

Interfaces When a class implements an interface, the is-a relationship applies. If Employee implements interface Payable, an Employee is-a Payable may be used as a type to refer to any object that implements it. This permits passing an object to a Payable parameter, or setting a Payable reference to an object. Inheritance & Polymorphism 43

The next example uses this class hierarchy. Italics indicate Employee is an abstract class. <<interface>> Payable Invoice Employee Salaried Employee Inheritance & Polymorphism 44

// Payable. java // Payable interface declaration. public interface Payable { double get. Payment. Amount(); // calculate payment; no implementation } // end interface Payable Inheritance & Polymorphism 45

this and super A subclass inherits the methods of its super class. When a subclass overrides such methods, it’s often necessary to invoke the equivalent method in the parent class and the keyword super lets you do this: class mybutton extends Button { public void set. Label(String label) { set. Font(myspecialfont); // change the font super. set. Label(label); // label the button } } Note that in a constructor any invocation of a superclass constructor must be the first statement - if not present: super(); is added by the compiler. The keyword this refers to the current object - useful when you want to pass the current object to another to allow the latter to execute the former’s methods. Inheritance & Polymorphism 46

instanceof If a superclass reference is used, it may refer to objects of its subclasses. If it is necessary to know which particular subclass an object belongs to, the instanceof operator can be used. Button b; My. Button mb; // where My. Button extends Button if (b instanceof Button) // is true if (mb instanceof My. Button) // is true if (mb instanceof Button) // is true if (b instanceof My. Button) // is false Inheritance & Polymorphism 47

Downcasting If a superclass variable refers to a subclass object, methods of the superclass can be called which behave polymorphically (dynamic-binding). However, attempting to call a subclass method from a superclass reference results in a compile error unless the superclass reference is downcast to the subclass. Inheritance & Polymorphism 48

Downcasting A subclass variable can be assigned to a superclass variable since a subclass is-a superclass. However, assigning a superclass variable to a subclass variable is a compile error without casting. Such casting is called “downcasting” since a higher type is cast to a lower type. superclass var = subclass var // ok because of is-a subclass var = superclass var // requires downcast Inheritance & Polymorphism 49

Inheritance Principles Common operations and fields belong to a superclass Use inheritance to model the is-a relationship Don’t use inheritance unless ALL inherited methods make sense. Use Polymorphism not type information Inheritance & Polymorphism 50
- Slides: 50