Aoop2013 Lect04
Aoop2013 Lect04
Programming
Inheritance, Interfaces
and Polymorphism
Kulwadee Somboonviwat
International College, KMITL
[email protected]
The software crisis
• software engineering: The practice of developing,
designing, documenting, testing large computer programs.
– Code Reuse
superclass
Employee
Lawyer Secretary
subclass subclass
class Employee {
…
}
– Example:
The distinction between hiding and overriding has important implications. The
version of the overridden method that gets invoked is the one in the subclass.
The version of the hidden method that gets invoked depends on whether it is
invoked from the superclass or the subclass. Let's look at an example that
contains two classes.
public class Animal {
public static void testClassMethod() {
System.out.println("The class" + " method in Animal.");
}
public void testInstanceMethod() {
System.out.println("The instance " + " method in Animal.");
}
}
Employee
LegalSecretary
Interacting with the superclass
Changes to common behavior
• Let's return to our previous company/employee example.
– Are we finished?
• The Employee subclasses are still incorrect.
– They have overridden getSalary to return
other values.
An unsatisfactory solution
public class LegalSecretary extends Secretary {
public double getSalary() {
return 55000.0;
}
...
}
public class Marketer extends Employee {
public double getSalary() {
return 60000.0;
}
...
}
super.method(parameters)
– Example:
public class LegalSecretary extends Secretary {
public double getSalary() {
double baseSalary = super.getSalary();
return baseSalary + 5000.0;
}
...
}
– This will require us to modify our Employee class and add some
new state and behavior.
public Lawyer() {
super(); // calls Employee() constructor
}
– Example:
public class Lawyer extends Employee {
public Lawyer(int years) {
super(years); // calls Employee constructor
}
...
}
LegalSecretary
Object variables
• You can store any object in a variable of type Object.
String s = o1.toString(); // ok
int len = o2.length(); // error
String line = o3.nextLine(); // error
p2 x 5 y 3
...
The equals method
• The equals method compares the state of objects.
if (str1.equals(str2)) {
System.out.println("the strings are
equal");
}
p2 x 5 y 3
...
Comparing different types
Point p = new Point(7, 2);
if (p.equals("hello")) { // should be false
...
}
if (o instanceof Point) {
// o is a Point; cast and compare it
Point other = (Point) o;
return x == other.x && y == other.y;
} else {
// o is not a Point; cannot be equal
return false;
}
}
Abstract Class
Abstract Classes
Circle Rectangle
-radius: double -width: double
-height: double
+Circle()
+Rectangle()
+Circle(radius: double)
+Rectangle(width: double, height: double)
+Circle(radius: double, color: String, filled:
+Rectangle(width: double, height: double,
boolean)
color: String, filled: boolean)
+getRadius(): double
+getWidth(): double
+setRadius(radius: double): void
+setWidth(width: double): void
+getDiameter(): double
+getHeight(): double
subclass +setHeight(height: double): void subclass
public abstract class GeometricObject {
private String color = "white";
private boolean filled;
private java.util.Date dateCreated;
/** Construct a default geometric object */
protected GeometricObject() {
dateCreated = new java.util.Date();
}
/** Construct a geometric object with the specified color
* and filled value */
protected GeometricObject(String color, boolean filled) {
this.color = color;
this.filled = filled;
}
/** Return color */
public String getColor() { return color; }
public void setColor(String color) { this.color = color; }
public boolean isFilled() { return filled; }
public void setFilled(boolean filled) { this.filled = filled; }
public java.util.Date getDateCreated() { return dateCreated; }
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;
}
/** Abstract method getArea */
public abstract double getArea();
displayGeometricObject(geoObject1);
displayGeometricObject(geoObject2);
}
– Overloading
same operator symbol or method name can be used in
different contexts.
– Subtype
When a subtype instance appears in a supertype context,
executing a supertype operation on the subtype instance
results in the subtype’s version of that operation executing.
– Parametric
Within a class declaration, a field name can associate with
different types and a method name can associate with different
parameter and return types.
But,
Circle C = new GeometricObject(); // ERROR!
Coding with polymorphism
• A variable of type T can hold an object of any subclass of T.
System.out.println(ed.getSalary()); // 50000.0
System.out.println(ed.getVacationForm()); // pink
Polymorphism and parameters
• You can pass any subtype of a parameter's type.
public class EmployeeMain {
public static void main(String[] args) {
Lawyer lisa = new Lawyer();
Secretary steve = new Secretary();
printInfo(lisa);
printInfo(steve);
}
public static void printInfo(Employee empl) {
System.out.println("salary: " + empl.getSalary());
System.out.println("v.days: " +
empl.getVacationDays());
System.out.println("v.form: " +
empl.getVacationForm());
System.out.println();
}
}
OUTPUT:
salary: 50000.0 salary: 50000.0
v.days: 15 v.days: 10
v.form: pink v.form: yellow
Polymorphism and arrays
• Arrays of superclass types can store any subtype as elements.
public class EmployeeMain2 {
public static void main(String[] args) {
Employee[] e = { new Lawyer(), new Secretary(),
new Marketer(), new LegalSecretary() };
for (int i = 0; i < e.length; i++) {
System.out.println("salary: " + e[i].getSalary());
System.out.println("v.days: " +
e[i].getVacationDays());
System.out.println();
}
}
}
Output:
salary: 50000.0
v.days: 15
salary: 50000.0
v.days: 10
salary: 60000.0
v.days: 10
salary: 55000.0
v.days: 10
Polymorphism problems
• 4-5 classes with inheritance relationships are shown.
• You must read the code and determine the client's output.
A polymorphism problem
• Suppose that the following four classes have been declared:
public class Foo {
public void method1() {
System.out.println("foo 1");
}
public void method2() {
System.out.println("foo 2");
}
public String toString() {
return "foo";
}
}
public class Bar extends Foo {
public void method2() {
System.out.println("bar 2");
}
}
public class Baz extends Foo {
public void method1() {
System.out.println("baz 1");
}
public String toString() {
return "baz";
}
}
public class Mumble extends Baz {
public void method2() {
System.out.println("mumble 2");
}
}
• What would be the output of the following client code?
Foo[] pity = {new Baz(), new Bar(), new Mumble(), new
Foo()};
for (int i = 0; i < pity.length; i++) {
System.out.println(pity[i]);
pity[i].method1();
pity[i].method2();
System.out.println();
}
Diagramming the classes
• Add classes from top (superclass) to bottom (subclass).
• You can cast only up and down the tree, not sideways.
Lawyer linda = new Lawyer();
((Secretary) linda).takeDictation("hi"); // error
Example:
– Example:
public class Bicycle implements Vehicle
{
...
}
– Example:
public class Banana implements Shape {
...
}