Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inheritance & Polymorphism1. 2 Introduction Besides composition, another form of reuse is inheritance. With inheritance, an object can inherit behavior.

Similar presentations


Presentation on theme: "Inheritance & Polymorphism1. 2 Introduction Besides composition, another form of reuse is inheritance. With inheritance, an object can inherit behavior."— Presentation transcript:

1 Inheritance & Polymorphism1

2 2 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).

3 Inheritance & Polymorphism3 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.

4 Inheritance & Polymorphism4 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.

5 Inheritance & Polymorphism5 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.

6 Inheritance & Polymorphism6 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 r ClassSubclassPackageWorld Publicxxxx Protectedxxx packagexx privatex

7 Inheritance & Polymorphism7 Inheritance is a form of software reusability in which new classes are created from existing classes by absorbing their attributes and behaviours and enhance these, with capabilities the new classes require. Polymorphism 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.

8 Inheritance & Polymorphism8 Polymorphism 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.

9 Inheritance & Polymorphism9 Animal FishFrogBird Superclass defines move method 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.

10 Inheritance & Polymorphism10 Polymorphism 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…..

11 Inheritance & Polymorphism11 Polymorphism The next example illustrates inheritance and polymorphism. When the “toString” 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.

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

13 Inheritance & Polymorphism13 Point, Circle Example (1a) public void setPoint( int a, int b ) { x = a; y = b; } public int getX() { return x; } public int getY() { return y; } public String toString() { return "[" + x + ", " + y + "]"; }

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

15 Inheritance & Polymorphism15 Point, Circle Example (2a) public void setRadius( double r ) { radius = ( r >= 0.0 ? r : 0.0 ); } public double getRadius() { return radius; } public double area() { return Math.PI * radius * radius; } public String toString() { return "Center = " + "[" + x + ", " + y + "]" + "; Radius = " + radius; }

16 Inheritance & Polymorphism16 Point, Circle Example (3) import java.text.DecimalFormat; import javax.swing.JOptionPane; public class Tester { public static void main( String args[] ) { Point pointRef, p; Circle circleRef, c; String output; p = new Point( 30, 50 ); c = new Circle( 2.7, 120, 89 ); output = "Point p: " + p.toString() + "\nCircle c: " + c.toString(); // use the "is a" relationship to refer to a Circle // with a Point reference pointRef = c; // assign Circle to pointRef output += "\n\nCircle c (via pointRef): " + pointRef.toString(); Polymorphism & Dynamic Binding

17 Inheritance & Polymorphism17 Point, Circle Example (4) // Use downcasting (casting a superclass reference to a subclass data type) to assign pointRef to circleRef circleRef = (Circle) pointRef; output += "\n\nCircle c (via circleRef): " + circleRef.toString(); DecimalFormat precision2 = new DecimalFormat( "0.00" ); output += "\nArea of c (via circleRef): " + precision2.format( circleRef.area() ); // Attempt to refer to Point object with Circle reference if ( p instanceof Circle ) { circleRef = (Circle) p; output += "\n\ncast successful"; } else output += "\n\np does not refer to a Circle"; JOptionPane.showMessageDialog( null, output,"Demonstrating the \"is a\" relationship", JOptionPane.INFORMATION_MESSAGE ); System.exit( 0 ); }

18 Inheritance & Polymorphism18 Point, Circle Example (5)

19 Inheritance & Polymorphism19 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.

20 Inheritance & Polymorphism20 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

21 Inheritance & Polymorphism21 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.

22 Inheritance & Polymorphism22 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 getName(); public abstract void Draw(); }

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

24 Inheritance & Polymorphism24 Case Study : Point,Circle,Cylinder (3) public int getX() { return x; } public int getY() { return y; } public String toString() { return "[" + x + ", " + y + "]"; } public String getName(){ return "Point"; } public void Draw() { JOptionPane.showMessageDialog(null,getName() + ": " + this); }

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

26 Inheritance & Polymorphism26 Case Study : Point,Circle,Cylinder (5) public double getRadius() { return radius; } public double area() { return Math.PI * radius * radius; } public String toString() { return "Center = " + "[" + x + ", " + y + "]" + "; Radius = " + radius; } public String getName() { return "Circle"; } public void Draw() { JOptionPane.showMessageDialog(null,getName() + ": " + this); }

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

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

29 Inheritance & Polymorphism29 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 toString() { return super.toString() + "; Height = " + height; } // Return the class name public String getName() { return "Cylinder"; } public void Draw() { JOptionPane.showMessageDialog(null,getName() + ": " + this); }

30 Inheritance & Polymorphism30 Case Study : Point,Circle,Cylinder (9) import java.text.DecimalFormat; import javax.swing.JOptionPane; 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, 10 ); Shape arrayOfShapes[]; arrayOfShapes = new Shape[ 3 ];

31 Inheritance & Polymorphism31 Case Study : Point,Circle,Cylinder (10) // aim arrayOfShapes[0] at subclass Point object arrayOfShapes[ 0 ] = point; // aim arrayOfShapes[1] at subclass Circle object arrayOfShapes[ 1 ] = circle; // aim arrayOfShapes[2] at subclass Cylinder object arrayOfShapes[ 2 ] = cylinder; point.Draw(); circle.Draw(); cylinder.Draw(); DecimalFormat precision2 = new DecimalFormat( "0.00" );

32 Inheritance & Polymorphism32 Case Study : Point,Circle,Cylinder (11) // Loop through arrayOfShapes and print the name, // area, and volume of each object. for ( int i = 0; i < arrayOfShapes.length; i++ ) { arrayOfShapes[ i ].Draw(); output = "\nArea = " + precision2.format( arrayOfShapes[ i ].area() ) + "\nVolume = " + precision2.format( arrayOfShapes[ i ].volume() ); JOptionPane.showMessageDialog( null, output,"Demonstrating Polymorphism", JOptionPane.INFORMATION_MESSAGE ); } System.exit( 0 ); } Polymorphism & Dynamic Binding

33 Inheritance & Polymorphism33 Case Study : Notes (12) Superclass Shape extends Object and consists of 3 public methods and contains no data (although it could). getName() & 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. area() & volume() are inherited (not overridden) from Shape getName() & 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.

34 Inheritance & Polymorphism34 Case Study : Notes (13) Class Circle is derived from Point area() is overridden as the area is different to that of a Point & volume() is inherited because a Circle has no volume getName() & 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 area() is overridden as the area is different to that of a Circle & volume() is overridden because a Cylinder has a volume getName() & 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

35 Inheritance & Polymorphism35 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. By using the implements keyword, a class can indicate that it implements that set of methods. This makes it unnecessary for related classes to share a common superclass or to directly subclass object. It’s possible for a class to implement several interfaces.

36 Inheritance & Polymorphism36 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

37 Inheritance & Polymorphism37 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.

38 Inheritance & Polymorphism38 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.

39 Inheritance & Polymorphism39 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.

40 Inheritance & Polymorphism40 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.

41 Inheritance & Polymorphism41 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.

42 Inheritance & Polymorphism42 Interfaces A class can inherit from only one direct superclass, but it can implement multiple interfaces. public class MyClass extends MySuper implements IFace1, IFace2, IFace3, … 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.

43 Inheritance & Polymorphism43 Interfaces When a class implements an interface, the is-a relationship applies. If Employee implements interface Payable, an Employee is-a Payable. 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.

44 Inheritance & Polymorphism44 > Payable InvoiceEmployee Italics indicate Employee is an abstract class. The next example uses this class hierarchy. Salaried Employee

45 Inheritance & Polymorphism45 // Payable.java // Payable interface declaration. public interface Payable { double getPaymentAmount(); // calculate payment; no implementation } // end interface Payable

46 Inheritance & Polymorphism46 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 setLabel(String label) { setFont(myspecialfont);// change the font super.setLabel(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.

47 Inheritance & Polymorphism47 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; MyButton mb;// where MyButton extends Button if (b instanceof Button)// is true if (mb instanceof MyButton)// is true if (mb instanceof Button)// is true if (b instanceof MyButton)// is false

48 Inheritance & Polymorphism48 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.

49 Inheritance & Polymorphism49 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

50 Inheritance & Polymorphism50 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


Download ppt "Inheritance & Polymorphism1. 2 Introduction Besides composition, another form of reuse is inheritance. With inheritance, an object can inherit behavior."

Similar presentations


Ads by Google