Presentation is loading. Please wait.

Presentation is loading. Please wait.

Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract.

Similar presentations


Presentation on theme: "Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract."— Presentation transcript:

1

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

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

4 class variable l class Circle { public static final double PI = 3.14159; public double x, y, r; l } l public class example{ public static void main(String[] args){ Circle.PI = 4;//Error } l } §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 l several methods of the same name can be defined, as long as the methods have different sets of parameters §Overriding l 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 int square(double x){ return x * x; } // second definition of method square with double argument // causes syntax error public double square(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 return type §Creating overloaded methods with identical parameters 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 l assume all shapes have x and y coordinates override Object's version of toString §Two subclasses of Shape l Rectangle add a new method changeWidth l 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 Rect extends Shape { 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 class Circle extends Shape { 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; } A Circle Class

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 §Assume class Rect is a subclass of class Shape, and it overrides the method getArea(). §Does this work? Rect r = new Rect(10, 20); Shape s = r; System.out.println("Area is " + s.getArea());

19 Object Variables §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 l The is-a relationship is met. A Rect is-a shape so s may point to it §This is a form of polymorphism and is used extensively in the Java Collection classes l Vector, ArrayList are lists of Objects Rect r = new Rect(10, 20); Shape s = r; System.out.println("Area is " + s.getArea());

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

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

22 §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? Type Compatibility Rect r = new Rect(5, 10); Shape s = r; s.changeWidth(20);

23 §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? Type Compatibility Rect r = new Rect(5, 10); Shape s = r; s.changeWidth(20); // syntax error

24 §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 l no changeWidth method in Shape class l must cast s to a rectangle; Type Compatibility Rect r = new Rect(5, 10); Shape s = r; s.changeWidth(20); // syntax error Rect r = new Rect(5, 10); Shape s = r; ((Rect)s).changeWidth(20); //Okay

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

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 instanceof operator Rect r = new Rect(5, 10); Circle c = new Circle(5); Shape s = c; ((Rect)s).changeWidth(4);

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

28 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 instanceof Book) System.out.println(“pub1 is a Book”); if (book1 instanceof Book) System.out.println(“book1 is a Book”); if (manual1 instanceof Book) System.out.println(“manual1 is a Book”); } instanceof example (syntax: expression instanceof ClassName)

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); l Shape s = c1; is equivalent to l 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. l 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 l refer to a superclass object with a superclass reference l refer to a subclass object with a subclass reference l referring to a subclass object with a superclass reference is safe, but such code can only refer to superclass members l 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 l that class may not be extended  A method in a class may be declared as final l that method may not be overridden l 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 abstract class defines a common interface for the various members of a class hierarchy. l an object of that type never exists and can never be instantiated. l a Shape or a Mammal §a method may be declared abstract in its header, after visibility modifier l no body to the method l all derived classes must eventually implement this method (or they must be abstract as well) l 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 l some languages support genericity via templates l 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 l a Graduate Teaching Assistant is-a Graduate Student. Graduate Teaching Assistant is-a Employee l a Student is-a Person. a Student is a SortableObject

38 Interfaces  A Java interface is a "pure abstract class". l Design only, no implementation. §Interfaces are declared in a way similar to classes but l consist only of public abstract methods l 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 greater than the parameter package java.lang public interface Comparable { public int compareTo( Object other ); }

40 §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 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 }

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 }


Download ppt "Outline §Review of the last class l class variables and methods l method overloading and overriding §Inheritance and polymorphism l polymorphism l abstract."

Similar presentations


Ads by Google