M251 Meeting 5
M251 Meeting 5
Polymorphism
1
Motivations
Suppose you will define classes to model
circles, rectangles, and triangles. These
classes have many common features.
What is the best way to design these
classes so to avoid redundancy? The
answer is to use inheritance.
2
Objectives
Inheritance Relationship
To define a subclass from a superclass.
To invoke the superclass’s constructors and methods using the
super keyword.
To override instance methods in the subclass.
To distinguish differences between overriding and overloading.
To explore the toString() method in the Object class.
To explore the equals() method in the Object class.
To discover polymorphism and dynamic binding.
To describe casting and explain why explicit down casting is
necessary.
To explore the equals() method in the Object class.
3
Inheritance Relationship between
classes
There are different types of relationships
between classes: has-a relationship(
Composition
Aggregation
Inheritance is-a relationship(
Aggregating Aggregated
Class Class
5
Composition Relationships
Composition is a stronger form of aggregation .
If the aggregating (composing) object is deleted,
6
Class Representation
An aggregation relationship is usually
represented as a data field in the aggregating
class. follows:
public class Name { public class Student { public class Address {
... private Name name; ...
} private Address address; }
...
}
Composition Aggregation
1 1 1..3 1
Name Student Address 7
Aggregation or Composition
8
Inheritance
SuperClass
Subclass
Subclass
Inheritance
UML notation
The Class Heirarchy
There are two types in Java hierarchy:
1. user-defined
2. Java class library.
public class Subclass-name extends Superclass-name
{
//methods and fields
}
Superclasses and Subclasses
SimpleGeometricObject
-color: String The color of the object (default: white).
-filled: boolean Indicates whether the object is filled with a color (default: false).
-dateCreated: java.util.Date The date when the object was created.
+GeometricObject() Creates a GeometricObject.
+GeometricObject(color: String, Creates a GeometricObject with the specified color and filled
filled: boolean) values.
+getColor(): String
+setColor(color: String): void
Returns the color.
Sets a new color.
SimpleGeometricObject
+isFilled(): boolean Returns the filled property.
+setFilled(filled: boolean): void Sets a new filled property. Circle
+getDateCreated(): java.util.Date Returns the dateCreated.
+toString(): String Returns a string representation of this object.
Rectangle
Circle Rectangle
-radius: double -width: double
+Circle() -height: double TestCircleR
+Circle(radius: double) +Rectangle() ectangle
+Circle(radius: double, color: String, +Rectangle(width: double, height: double)
filled: boolean) +Rectangle(width: double, height: double
+getRadius(): double color: String, filled: boolean)
+setRadius(radius: double): void +getWidth(): double
+getArea(): double +setWidth(width: double): void Run
+getPerimeter(): double +getHeight(): double
+getDiameter(): double +setHeight(height: double): void
+printCircle(): void +getArea(): double
+getPerimeter(): double
16
Example: SimpleGeometricObject Class
import java.util.Date;
public class SimpleGeometricObject { public boolean isFilled()
private String color = "white"; { return filled; }
private boolean filled;
private Date dateCreated; public void setFilled(boolean
filled) { this.filled = filled;}
public SimpleGeometricObject() {
dateCreated = new java.util.Date(); public Date getDateCreated()
} {
public SimpleGeometricObject(String return dateCreated;
color, boolean filled) { }
dateCreated = new Date();
this.color = color; public String toString() {
this.filled = filled; return "created on " +
} dateCreated +
public String getColor() { return "\ncolor: " + color +
color; } " and filled: " +
filled;
public void setColor(String color) }
{this.color = color;}
}
Continue: Circle class
public class Circle extends
SimpleGeometricObject { public double getArea()
private double radius; { return radius * radius *
Math.PI; }
public Circle() { }
public double getDiameter()
public Circle(double radius)
{ return 2 * radius; }
{ this.radius = radius; }
public double getPerimeter()
public Circle(double radius, String
{ return 2 * radius * Math.PI; }
color, boolean filled)
{ this.radius = radius;
public void printCircle() {
setColor(color);
System.out.println("The circle
setFilled(filled); }
is created " + getDateCreated()
public double getRadius()
+ " and the radius is " +
{ return radius; }
radius);
public void setRadius(double radius) }
{ this.radius = radius; } }
Continue: Class Rectangle
public class Rectangle extends
SimpleGeometricObject {
public void setWidth(double width)
private double width, height;
{ this.width = width; }
public Rectangle() { } public double getHeight()
public Rectangle( double w, double h) { return height; }
22
Using the Keyword super
23
CAUTION
25
Defining a Subclass
A subclass inherits from a superclass. A
subclass can also:
Have new properties
Have new methods
Override the methods of the superclass
26
Calling Superclass Methods
You could rewrite the printCircle() method in the
Circle class as follows:
27
Overriding Methods in the
Superclass
A subclass inherits methods from a superclass. Sometimes it
is necessary for the subclass to modify the implementation of
a method defined in the superclass. This is referred to as
method overriding.
public class Circle extends GeometricObject {
// Other methods are omitted
28
NOTE
An instance method can be overridden
only if it is accessible.
Thus a private method cannot be
overridden, because it is not accessible
outside its own class.
If a method defined in a subclass is
private in its superclass, the two methods
are completely unrelated. 29
NOTE
class B { class B {
public void p(double i) { public void p(double i) {
System.out.println(i * 2); System.out.println(i * 2);
} }
} }
32
Overriding
public class Parent{ public class Test{
public void method(int i) public static void main()
{ System.out.println(“parent:”+i);} { Parent p = new Parent();
} Child c = new Child();
public class Child extends Parent { Parent k = new Child();
public void method(int i) p.method(2);
{ System.out.println(“child:”+i*2);} c.metod(2);
} k.method(2);
}
}
Example:
34
Visibility Modifiers and
Accessor/Mutator Methods
By default, the class, variable, or method can be
accessed by any class in the same package.
public
The class, data, or method is visible to any class in any package using
qualified name (a reference and a dot notation).
private
The data or methods can be accessed only by the declaring class. The get and
set methods are used to read and modify private properties.
Protected
The data or methods are accessible inside class where they are declared, and
inside subclasses. All class in the same package can access protected member
using qualified name.
No modifier: default members can be accessed by all classes in the same 35
package using qualified name
The private modifier restricts access to within a class, the default modifier
restricts access to within a package, and the public modifier enables unrestricted
access.
36
The default modifier on a class restricts access to within a package, and the
public modifier enables unrestricted access.
37
The protected Modifier
The protected modifier can be applied on data
and methods in a class. A protected data or a
protected method in a public class can be
accessed by any class in the same package or its
subclasses, even if the subclasses are in a
different package.
private, default, protected, public
Visibility increases
38
Accessibility Summary
public
protected -
default - -
private - - -
39
Visibility Modifiers
package p1;
public class C1 { public class C2 {
public int x; C1 o = new C1();
protected int y; can access o.x;
int z; can access o.y;
private int u; can access o.z;
cannot access o.u;
protected void m() {
} can invoke o.m();
} }
package p2;
40
A Subclass Cannot Weaken the
Accessibility
A subclass may override a protected
method in its superclass and change its
visibility to public.
However, a subclass cannot weaken the
accessibility of a method defined in the
superclass. For example, if a method is
defined as public in the superclass, it must
be defined as public in the subclass.
41
NOTE
42
The final Modifier
The final class cannot be extended:
final class Math {
...
}
43
The Object Class and Its Methods
Every class in Java is descended from the
java.lang.Object class. If no inheritance is
specified when a class is defined, the
superclass of the class is Object.
44
The toString() method in Object
The toString() method returns a string representation of the
object. The default implementation returns a string consisting
of a class name of which the object is an instance, the at sign
(@), and a number representing this object.
46
NOTE
The == comparison operator is used for comparing
two primitive data type values or for determining
whether two objects have the same references.
The equals method is intended to test whether two
objects have the same contents, provided that the
method is modified in the defining class of the
objects.
The == operator is stronger than the equals
method, in that the == operator checks whether the
two reference variables refer to the same object.
47
The instanceof Operator
48
Exercise
Cn Cn-1 ..... C2 C1
54
Generic Programming
public class PolymorphismDemo {
public static void main(String[] args) {
m(new GraduateStudent()); Polymorphism allows methods to be
m(new Student());
m(new Person()); used generically for a wide range of
}
m(new Object()); object arguments. This is known as
generic programming.
public static void m(Object x) {
System.out.println(x.toString()); If a method’s parameter type is a
}
} superclass (e.g., Object), you may
class GraduateStudent extends Student {
pass an object to this method of any of
} the parameter’s subclasses (e.g.,
class Student extends Person { Student or String).
public String toString() {
return "Student"; When an object (e.g., a Student
} object or a String object) is used in the
}
method, the particular implementation
class Person extends Object {
public String toString() {
of the method of the object that is
return "Person"; invoked (e.g., toString) is determined
}
} dynamically.
55
Casting Objects
You have already used the casting operator to convert
variables of one primitive type to another. Casting can
also be used to convert an object of one class type to
another within an inheritance hierarchy.
In the preceding section, the statement
m(new Student());
Orange x = (Orange)Fruit;
58
TIP
To help understand casting, you may also
consider the analogy of fruit, apple, and
orange with the Fruit class as the
superclass for Apple and Orange. An
apple is a fruit, so you can always safely
assign an instance of Apple to a variable
for Fruit.
However, a fruit is not necessarily an
apple, so you have to use explicit casting
to assign an instance of Fruit to a variable
of Apple.
59
Please Solve the Activity of Meeting 5.
60