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

41

Transcript of Outline §Review of the last class l class variables and methods l method overloading and overriding...

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

Outline

Review of the last class class variables and methods method overloading and overriding

Inheritance and polymorphism polymorphism abstract classes and interface

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

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?

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

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.

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

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?

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

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) //Errorreturn c;

else return this; //Error

}}

static methods may not manipulate any instance variables!

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

Method Overloading and Overriding

What is the difference?

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

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

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

Overloadingpublic class Overload {

// first definition of method squarepublic int square(double x){

return x * x;}// second definition of method squarepublic double square(double y){

return y * y;}

} //end class Overload

Is this correct?

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

Overloadingpublic class Overload {

// first definition of method square with double argumentpublic int square(double x){

return x * x;}// second definition of method square with double argument// causes syntax errorpublic double square(double y){

return y * y;}

} //end class Overload

The compiler would not know how to distinguish between the two square methods.

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

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

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

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.

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

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

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

A Shape classpublic 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;

}}

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

A Rectangle Classpublic 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; }}

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

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

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

PolymorphismIf 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”

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

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());

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

Object Variables

The above code works if Rect extends ShapeAn 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 s may

point to it

This is a form of polymorphism and is used extensively in the Java Collection classes

Vector, ArrayList are lists of Objects

Rect r = new Rect(10, 20);

Shape s = r;

System.out.println("Area is " + s.getArea());

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

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() );

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

More Polymorphism

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

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() );

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

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);

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

polymorphism allows s to point at a Rect object but there are limitations

The above code does not workHow can you modify it a little to make it work

without changing the classes definitions?

Type CompatibilityRect r = new Rect(5, 10);Shape s = r;s.changeWidth(20); // syntax error

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

polymorphism allows s to point at a Rect object but there are limitations

The above code does not workStatically s is declared to be a shape

no changeWidth method in Shape class must cast s to a rectangle;

Type CompatibilityRect 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

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

Problems with Casting

Does this work?

Rect r = new Rect(5, 10);Circle c = new Circle(5);Shape s = c;((Rect)s).changeWidth(4);

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

Problems with CastingThe following code compiles but an exception

is thrown at runtime

Casting must be done carefully and correctlyIf 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);

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

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);

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

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)

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

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;

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

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

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

The role of final in InheritanceA 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.

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

Abstract Classes and MethodsAn abstract class 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

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

abstract class Shape {

public Shape() { id = ++count; }

public int getId() { return id; }

public abstract double getArea();

private static int count = 0; private int id;}

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

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;}

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

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;}

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

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

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

Multiple InheritanceInheritance models the "is-a" relationship

between real world thingsone of the benefits is code reuse, completing

programs faster, with less effortin 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

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

InterfacesA 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

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

Common Interfaces in JavaOne 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 );}

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

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

}

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

Polymorphism Againpublic 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}