1 / 41

Java

Java. Inheritance and Polymorphism. Outline. Review of the last class class variables and methods method overloading and overriding Inheritance and polymorphism polymorphism abstract classes and interface. class Circle { public static final double PI = 3.14159;

corbin
Download Presentation

Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Java Inheritance and Polymorphism

  2. Outline • Review of the last class • class variables and methods • method overloading and overriding • Inheritance and polymorphism • polymorphism • abstract classes and interface

  3. class Circle { • public static final double PI = 3.14159; • public double x, y, r; • } • public class example{ • public static void main(String[] args){ • Circle.PI = 4; • } • } • Is this correct?

  4. class variable • class Circle { • public static final double PI = 3.14159; • public double x, y, r; • } • public class example{ • public static void main(String[] args){ • Circle.PI = 4; //Error • } • } • The final keyword means that this variable can never be changed.

  5. public class Circle { public double x, y, r; // an class method. Returns the bigger of two circles. public static Circle bigger(Circle c){ if(c.r > r) return c; else return this; } //other methods omitted here. } • Is this correct?

  6. class method public class Circle { public double x, y, r; // an class method. Returns the bigger of two circles. public static Circle bigger(Circle c){ if(c.r > r) //Error return c; else return this; //Error } } • static methods may not manipulate any instance variables!

  7. Method Overloading and Overriding • What is the difference?

  8. Overloading and Overriding • What is the difference? • Overloading • several methods of the same name can be defined, as long as the methods have different sets of parameters • Overriding • a subclass can redefine a superclass method by using the same signature

  9. Overloading public class Overload { // first definition of method square public int square(double x){ return x * x; } // second definition of method square public double square(double y){ return y * y; } } //end class Overload • Is this correct?

  10. Overloading public class Overload { // first definition of method square with double argument public intsquare(double x){ return x * x; } // second definition of method square with double argument // causes syntax error public doublesquare(double y){ return y * y; } } //end class Overload • The compiler would not know how to distinguish between the two square methods.

  11. Overloading • Overloading methods are distinguished by their signature -- a combination of the method’s name and its parameter types • Methods can not be distinguished by returntype • Creating overloaded methods with identicalparameters lists and different return types is a syntax error

  12. Overloading and overriding • A redefinition of a superclass method in a subclass need not have the same signature as the superclass method. Such a redefinition is not method overriding; rather it is an example of overloading. • It is syntax error if a method in a superclass and a method in a subclass have the same signature but a different return type.

  13. Shape Classes • We have a class called Shape • assume all shapes have x and y coordinates • override Object's version of toString • Two subclasses of Shape • Rectangle add a new method changeWidth • Circle

  14. A Shape class public class Shape { private double dMyX, dMyY; public Shape() { this(0,0);} public Shape (double x, double y) { dMyX = x; dMyY = y; } public String toString() { return "x: " + dMyX + " y: " + dMyY; } public double getArea() { return 0; } }

  15. A Rectangle Class public class RectextendsShape{ private double dMyWidth, dMyHeight; public Rect(double width, double height) { dMyWidth = width; dMyHeight = height; } public String toString() { return " width " + dMyWidth + " height " + dMyHeight; } public double getArea() { return dMyWidth * dMyHeight; } public void changeWidth(double width){ dMyWidth = width; } }

  16. A Circle Class class CircleextendsShape { private double radius; private static final double PI = 3.14159; public Circle(double rad){ radius = rad; } public double getArea() { return PI * radius * radius; } public String toString() { return " radius " + radius; } }

  17. Polymorphism • If class Rect is derived from class Shape, an operation that can be performed on an object of class Shape can also be performed on an object of class Rect • When a request is made through a superclass reference to use a method, Java choose the correct overridden method polymorphically in the appropriate subclass associated with the object • Polymorphism means “different forms”

  18. Object Variables Rect r = new Rect(10, 20); Shape s = r; System.out.println("Area is " + s.getArea()); • Assume class Rect is a subclass of class Shape, and it overrides the method getArea(). • Does this work?

  19. Object Variables Rect r = new Rect(10, 20); Shape s = r; System.out.println("Area is " + s.getArea()); • The above code works if Rect extends Shape • An object variable may point to an object of its base type or a descendant in the inheritance chain • The is-a relationship is met. A Rect is-a shape so smay point to it • This is a form of polymorphism and is used extensively in the Java Collection classes • Vector, ArrayList are lists of Objects

  20. More Polymorphism Circle c = new Circle(5);Rect r = new Rect(5, 3);Shape s = null;if( Math.random(100) % 2 == 0 )s = c;elses = r;System.out.println( "Shape is " + s.toString() ); • Assuming Circle and Rect are subclasses of Shape, and have both overriddentoString(), which version gets called?

  21. More Polymorphism Circle c = new Circle(5);Rect r = new Rect(5, 3);Shape s = null;if( Math.random(100) % 2 == 0 )s = c;elses = r;System.out.println( "Shape is " + s.toString() ); • Assuming Circle and Rect have both overridden toString which version gets called? • code works because s is polymorphic • method call determined at run time by dynamic binding

  22. Type Compatibility Rect r = new Rect(5, 10);Shape s = r;s.changeWidth(20); • Assume class Rect is a subclass of class Shape, and it has a new method changeWidth(double width), which its super class does not have. • Does this work?

  23. Type Compatibility Rect r = new Rect(5, 10);Shape s = r;s.changeWidth(20); // syntax error • polymorphism allows s to point at a Rect object but there are limitations • The above code does not work • How can you modify it a little to make it work without changing the classes definitions?

  24. Type Compatibility Rect r = new Rect(5, 10);Shape s = r;s.changeWidth(20); // syntax error • polymorphism allows s to point at a Rect object but there are limitations • The above code does not work • Statically s is declared to be a shape • no changeWidth method in Shape class • must casts to a rectangle; Rect r = new Rect(5, 10);Shape s = r;((Rect)s).changeWidth(20); //Okay

  25. Problems with Casting Rect r = new Rect(5, 10);Circle c = new Circle(5);Shape s = c;((Rect)s).changeWidth(4); • Does this work?

  26. Problems with Casting • The following code compiles but an exception is thrown at runtime • Casting must be done carefully and correctly • If unsure of what type object will be then use the instanceofoperator Rect r = new Rect(5, 10);Circle c = new Circle(5);Shape s = c;((Rect)s).changeWidth(4);

  27. instanceof Rect r = new Rect(5, 10);Circle c = new Circle(5);Shape s = c; if(sinstanceofRect) ((Rect)s).changeWidth(4); • syntax: expression instanceof ClassName

  28. instanceof example(syntax: expression instanceof ClassName) Assume Manual is a Book, and Book is a Publication. Output? public class InstanceofDemo { public static void main(String args[]) { Publication pub1 = new Publication(); Book book1 = new Book(); Manual manual1 = new Manual(); if (pub1 instanceofBook) System.out.println(“pub1 is a Book”); if (book1 instanceofBook) System.out.println(“book1 is a Book”); if (manual1 instanceof Book) System.out.println(“manual1 is a Book”); } }

  29. Casting • It is always possible to convert a subclass to a superclass. For this reason, explicit casting can be omitted. For example, • Circle c1 = new Circle(5); • Shape s = c1; is equivalent to • Shape s = (Shape)c1; • Explicit casting must be used when casting an object from a superclass to a subclass. This type of casting may not always succeed. • Circle c2 = (Circle) s;

  30. Implicit Subclass-Object-to-Superclass-Object Conversion • Four possible ways to mix and match superclass references and subclass references with superclass objects and subclass objects • refer to a superclass object with a superclass reference • refer to a subclass object with a subclass reference • referring to a subclass object with a superclass reference is safe, but such code can only refer to superclass members • referring to a superclass object with a subclass reference is a syntax error

  31. The role of final in Inheritance • A class may be declared as final • that class may not be extended • A method in a class may be declared as final • that method may not be overridden • guarantees behavior in all descendants • can speed up a program by allowing static binding (binding or determination at compile time what code will actually be executed) • All static methods and private methods are implicitly final, as are all methods of a final class.

  32. Abstract Classes and Methods • An abstractclass defines a common interface for the various members of a class hierarchy. • an object of that type never exists and can never be instantiated. • a Shape or a Mammal • a method may be declared abstract in its header, after visibility modifier • no body to the method • all derived classes must eventually implement this method (or they must be abstract as well) • any class with 1 or more abstract methods must be an abstract class

  33. abstract class Shape { public Shape() { id = ++count; } public int getId() { return id; } public abstract double getArea(); private static int count = 0; private int id; }

  34. class Rectangle extends Shape { public Rectangle(int ul_x, int ul_y, int lr_x, int lr_y) { upperLeft = new Point(ul_x, ul_y); lowerRight = new Point(lr_x, lr_y); } public double getArea() { double result = Math.abs(upperLeft.x - lowerRight.x) * Math.abs(upperLeft.y - lowerRight.y); return result; } private Point upperLeft; private Point lowerRight; }

  35. import java.awt.Point; class Circle extends Shape { public Circle(int x, int y, int rad) { center = new Point(x, y); radius = rad; } public double getArea() { return 4 * Math.atan(1.0) * radius * radius; // pi == 4 * atan(1.0) } private int radius; private Point center; }

  36. Genericity • One of the goals of OOP is the support of code reuse to allow more efficient program development • If an algorithm is essentially the same, but the code would vary based on the data type genericity allows only a single version of that code to exist • some languages support genericity via templates • in Java, polymorphism and the inheritance requirement along with interfaces are used

  37. Multiple Inheritance • Inheritance models the "is-a" relationship between real world things • one of the benefits is code reuse, completing programs faster, with less effort • in the real world a thing can have "is-a" relationships with several other things • a Graduate Teaching Assistant is-a Graduate Student. Graduate Teaching Assistant is-a Employee • a Student is-a Person. a Student is a SortableObject

  38. Interfaces • A Java interface is a "pure abstract class". • Design only, no implementation. • Interfaces are declared in a way similar to classes but • consist only of public abstract methods • public final fields • A Java class extends exactly one other class, but can implement as many interfaces as desired

  39. Common Interfaces in Java • One of the most interesting interfaces is: Comparable • compareTo should return an int <0 if the calling object is less than the parameter, 0 if they are equal, and an int >0 if the calling object is greater than the parameter package java.lang public interface Comparable{ public int compareTo( Object other );}

  40. Implementing an Interface public class Card implements Comparable{ public int compareTo(Object otherObject){ Card other = (Card)otherObject; int result = mySuit - other.mySuit; if(result == 0) result = myValue - other.myValue; return result; } // other methods not shown} • If a class declares that it will implement an interface, but does not provide an implementation of all the methods in that interface, that class must be abstract

  41. Polymorphism Again public static sort(Comparable[] list){ Comparable temp; int smallest; for(int i = 0; i < list.length - 1; i++) { small = i; for(int j = i + 1; j < list.length; j++) { if( list[j].compareTo(list[small]) < 0) small = j; } // end of j loop temp = list[i]; list[i] = list[small]; list[small] = temp; } // end of i loop}

More Related