OOP Inheritance Polymorphism Java Programming Tutorial PDF
OOP Inheritance Polymorphism Java Programming Tutorial PDF
Point.java
1 // The Point class definition
2 public class Point {
3 // Private member variables
4 private int x, y; // (x, y) co-ordinates
5
1 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
6 // Constructors
7 public Point(int x, int y) {
8 this.x = x;
9 this.y = y;
10 }
11 public Point() { // default (no-arg) constructor
12 x = 0;
13 y = 0;
14 }
15
16 // Public getter and setter for private variables
17 public int getX() {
18 return x;
19 }
20 public void setX(int x) {
21 this.x = x;
22 }
23 public int getY() {
24 return y;
25 }
26 public void setY(int y) {
27 this.y = y;
28 }
29
30 // toString() to describe itself
31 public String toString() {
32 return "(" + x + "," + y + ")";
33 }
34 }
UML Notation: In UML notations, composition is represented as a diamond-head line pointing to its constituents.
2 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
Line.java
1 // The Line class definition
2 public class Line {
3 // Private member variables
4 Point begin, end; // Declare begin and end as instances of Point
5
6 // Constructors
7 public Line(int x1, int y1, int x2, int y2) {
8 begin = new Point(x1, y1); // Construct Point instances
9 end = new Point(x2, y2);
10 }
11 public Line(Point begin, Point end) {
12 this.begin = begin; // Caller constructed Point instances
13 this.end = end;
14 }
15
16 // Public getter and setter for private variables
17 public Point getBegin() {
18 return begin;
19 }
20 public Point getEnd() {
21 return end;
22 }
23 public void setBegin(Point begin) {
24 this.begin = begin;
25 }
26 public void setEnd(Point end) {
27 this.end = end;
28 }
29
30 public int getBeginX() {
31 return begin.getX();
32 }
33 public void setBeginX(int x) {
34 begin.setX(x);
35 }
36 public int getBeginY() {
37 return begin.getY();
38 }
39 public void setBeginY(int y) {
40 begin.setY(y);
41 }
42 public void setBeginXY(int x, int y) {
43 begin.setX(x);
44 begin.setY(y);
45 }
46 public int getEndX() {
47 return end.getX();
48 }
49 public void setEndX(int x) {
50 end.setX(x);
51 }
52 public int getEndY() {
53 return end.getY();
54 }
55 public void setEndY(int y) {
56 end.setY(y);
57 }
58 public void setEndXY(int x, int y) {
3 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
59 end.setX(x);
60 end.setY(y);
61 }
62
63 public String toString() {
64 return "Line from " + begin + " to " + end;
65 }
66
67 public double getLength() {
68 int xDiff = begin.getX() - end.getX();
69 int yDiff = begin.getY() - end.getY();
70 return Math.sqrt(xDiff*xDiff + yDiff*yDiff);
71 }
72 }
2. Inheritance
In OOP, we often organize classes in hierarchy to avoid duplication and reduce redundancy. The classes in the lower
hierarchy inherit all the variables (static attributes) and methods (dynamic behaviors) from the higher hierarchies. A class
in the lower hierarchy is called a subclass (or derived, child, extended class). A class in the upper hierarchy is called a
superclass (or base, parent class). By pulling out all the common variables and methods into the superclasses, and leave
the specialized variables and methods in the subclasses, redundancy can be greatly reduced or eliminated as these
common variables and methods do not need to be repeated in all the subclasses. For example,
4 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
A subclass inherits all the variables and methods from its superclasses, including its immediate parent as well as all the
ancestors. It is important to note that a subclass is not a "subset" of a superclass. In contrast, subclass is a "superset" of
a superclass. It is because a subclass inherits all the variables and methods of the superclass; in addition, it extends the
superclass by providing more variables and methods.
UML Notation: The UML notation for inheritance is a solid line with a
hollow arrowhead leading from the subclass to its superclass. By convention,
superclass is drawn on top of its subclasses as shown.
Cylinder.java
1 // Define Cylinder class, which is a subclass of Circle
2 public class Cylinder extends Circle {
3 private double height; // Private member variable
4
5 public Cylinder() { // constructor 1
6 super(); // invoke superclass' constructor Circle()
7 height = 1.0;
5 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
8 }
9 public Cylinder(double radius, double height) { // Constructor 2
10 super(radius); // invoke superclass' constructor Circle(radius)
11 this.height = height;
12 }
13
14 public double getHeight() {
15 return height;
16 }
17 public void setHeight(double height) {
18 this.height = height;
19 }
20 public double getVolume() {
21 return getArea()*height; // Use Circle's getArea()
22 }
23 }
Keep the "Cylinder.java" and "TestCylinder.java" in the same directory as "Circle.class" (because we are
reusing the class Circle). Compile and run the program. The expected output is as follows:
Radius is 1.0 Height is 1.0 Color is red Base area is 3.141592653589793 Volume is 3.141592653589793
Radius is 5.0 Height is 2.0 Color is red Base area is 78.53981633974483 Volume is 157.07963267948966
For example, the inherited method getArea() in a Cylinder object computes the base area of the cylinder. Suppose
that we decide to override the getArea() to compute the surface area of the cylinder in the subclass Cylinder. Below
are the changes:
6 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
If getArea() is called from a Circle object, it computes the area of the circle. If getArea() is called from a
Cylinder object, it computes the surface area of the cylinder using the overridden implementation. Note that you have
to use public accessor method getRadius() to retrieve the radius of the Circle, because radius is declared
private and therefore not accessible to other classes, including the subclass Cylinder.
But if you override the getArea() in the Cylinder, the getVolume() (=getArea()*height) no longer works. It is
because the overridden getArea() will be used in Cylinder, which does not compute the base area. You can fix this
problem by using super.getArea() to use the superclass' version of getArea(). Note that super.getArea() can
only be issued from the subclass definition, but no from an instance created, e.g. c1.super.getArea(), as it break the
information hiding and encapsulation principle.
Annotations are not programming constructs. They have no effect on the program output. It is only used by the
compiler, discarded after compilation, and not used by the runtime.
The keyword super allows the subclass to access superclass' methods and variables within the subclass' definition. For
example, super() and super(argumentList) can be used invoke the superclass’ constructor. If the subclass
overrides a method inherited from its superclass, says getArea(), you can use super.getArea() to invoke the
superclass' version within the subclass definition. Similarly, if your subclass hides one of the superclass' variable, you
can use super.variableName to refer to the hidden variable within the subclass definition.
In the body of a constructor, you can use super(args) to invoke a constructor of its immediate superclass. Note that
super(args), if it is used, must be the first statement in the subclass' constructor. If it is not used in the constructor,
7 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
Java compiler automatically insert a super() statement to invoke the no-arg constructor of its immediate superclass.
This follows the fact that the parent must be born before the child can be born. You need to properly construct the
superclasses before you can construct the subclass.
8 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
Superclass Point.java
As in above example.
Subclass Point3D.java
1 // Define Point3D, subclass of Point
2 public class Point3D extends Point {
3 // Private member variable
4 private int z;
5
6 // Constructors
7 public Point3D() { // default no-arg constructor
8 super(); // Call superclass' no-arg constructor Point()
9 z = 0;
10 }
11 public Point3D(int x, int y, int z) {
12 super(x, y); // Call superclass' Point(x, y)
13 this.z = z;
14 }
15
16 // Public getter/setter for private variable
17 public int getZ() {
18 return z;
19 }
20 public void setZ(int z) {
21 this.z = z;
22 }
23
24 // toString() to describe itself
25 @Override
26 public String toString() {
27 return "(" + super.getX() + "," + super.getY() + "," + z + ")";
28 }
29 }
9 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
Superclass Person.java
// Define superclass Person
public class Person {
// Instance variables
private String name;
private String address;
// Constructor
public Person(String name, String address) {
this.name = name;
this.address = address;
}
// Getters
public String getName() {
10 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
return name;
}
public String getAddress() {
return address;
}
// Constructor
public Student(String name, String address) {
super(name, address);
numCourses = 0;
courses = new String[MAX_COURSES];
grades = new int[MAX_COURSES];
}
@Override
public String toString() {
return "Student: " + super.toString();
}
11 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
// Instance variables
private int numCourses; // number of courses taught currently
private String[] courses; // course codes
private static final int MAX_COURSES = 10; // maximum courses
// Constructor
public Teacher(String name, String address) {
super(name, address);
numCourses = 0;
courses = new String[MAX_COURSES];
}
@Override
public String toString() {
return "Teacher: " + super.toString();
}
12 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
3.3 Exercises
LINK TO EXERCISES
4.1 "A line is composed of 2 points" vs. "A line is a point extended by
another point"
Recall that there are two ways of reusing existing classes: composition and inheritance. We have seen that a Line class
can be implemented using composition of Point class - "A line is composed of two points".
13 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
Superclass Point.java
As above.
Subclass LineSub.java
1 // Define class LineSub, subclass of Point
2 public class LineSub extends Point { // Inherited the begin point
3 // Private member variables
4 Point end; // Declare end as instance of Point
5
6 // Constructors
7 public LineSub(int x1, int y1, int x2, int y2) {
8 super(x1, y1);
9 end = new Point(x2, y2); // Construct Point instances
10 }
11 public LineSub(Point begin, Point end) {
12 super(begin.getX(), begin.getY());
13 this.end = end;
14 }
15
16 // Public getter and setter for private variables
17 public Point getBegin() {
18 return this; // upcast to Point (polymorphism)
19 }
20 public Point getEnd() {
21 return end;
22 }
23 public void setBegin(Point begin) {
24 super.setX(begin.getX());
25 super.setY(begin.getY());
26 }
27 public void setEnd(Point end) {
28 this.end = end;
29 }
30
31 public int getBeginX() {
32 return super.getX(); // inherited, super is optional
33 }
14 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
15 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
19 }
Study both versions of the Line class (Line and LineSub). I suppose that it is easier to say that "A line is composed of
two points" than that "A line is a point extended by another point".
4.2 Exercises
LINK TO EXERCISES ON COMPOSITION VS INHERITANCE
5. Polymorphism
The word "polymorphism" means "many forms". It comes from Greek word "poly" (means many) and "morphos" (means
form). For examples, in chemistry, carbon exhibits polymorphism because it can be found in more than one form:
graphite and diamond. Each of the form has it own distinct properties.
5.1 Substitutability
A subclass possesses all the attributes and operations of its
superclass (because a subclass inherited all attributes and
operations from its superclass). This means that a subclass
object can do whatever its superclass can do. As a result, we
can substitute a subclass instance when a superclass instance
is expected, and everything shall work fine. This is called
substitutability.
You can invoke all the methods defined in the Circle class
for the reference c1, (which is actually holding a Cylinder object), e.g. c1.getRadius() and c1.getColor(). This is
because a subclass instance possesses all the properties of its superclass.
However, you cannot invoke methods defined in the Cylinder class for the reference c1, e.g. c1.getHeight() and
c1.getVolume(). This is because c1 is a reference to the Circle class, which does not know about methods defined
in the subclass Cylinder.
c1 is a reference to the Circle class, but holds an object of its subclass Cylinder. The reference c1, however, retains
its internal identity. In our example, the subclass Cylinder overrides methods getArea() and toString().
c1.getArea() or c1.toString() invokes the overridden version defined in the subclass Cylinder, instead of the
version defined in Circle. This is because c1 is in fact holding a Cylinder object internally.
Summary
1. A subclass instance can be assigned (substituted) to a superclass' reference.
16 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
2. Once substituted, we can invoke methods defined in the superclass; we cannot invoke methods defined in the
subclass.
3. However, if the subclass overrides inherited methods from the superclass, the subclass (overridden) versions will
be invoked.
Circle c1 = new Cylinder(); // Compiler checks to ensure that R-value is a subclass of L-value.
Circle c2 = new String(); // Compilation error: incompatible types
Downcasting requires explicit type casting operator in the form of prefix operator (new-type). Downcasting is not
always safe, and throws a runtime ClassCastException if the instance to be downcasted does not belong to the
correct subclass. A subclass object can be substituted for its superclass, but the reverse is not true.
Compiler may not be able to detect error in explicit cast, which will be detected only at runtime. For example,
17 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
Shape.java
// Define superclass Shape
public class Shape {
// Private member variable
private String color;
// Constructor
public Shape (String color) {
this.color = color;
}
@Override
public String toString() {
return "Shape of color=\"" + color + "\"";
}
18 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
Take note that we have a problem on writing the getArea() method in the Shape class, because the area cannot be
computed unless the actual shape is known. We shall print an error message for the time being. In the later section, I
shall show you how to resolve this problem.
We can then derive subclasses, such as Triangle and Rectangle, from the superclass Shape.
Rectangle.java
// Define Rectangle, subclass of Shape
public class Rectangle extends Shape {
// Private member variables
private int length;
private int width;
// Constructor
public Rectangle(String color, int length, int width) {
super(color);
this.length = length;
this.width = width;
}
@Override
public String toString() {
return "Rectangle of length=" + length + " and width=" + width + ", subclass of " + super.toString();
}
@Override
public double getArea() {
return length*width;
}
}
Triangle.java
// Define Triangle, subclass of Shape
public class Triangle extends Shape {
// Private member variables
private int base;
private int height;
// Constructor
public Triangle(String color, int base, int height) {
super(color);
this.base = base;
this.height = height;
}
@Override
public String toString() {
return "Triangle of base=" + base + " and height=" + height + ", subclass of " + super.toString();
}
@Override
19 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
The subclasses override the getArea() method inherited from the superclass, and provide the proper implementations
for getArea().
TestShape.java
In our application, we could create references of Shape, and assigned them instances of subclasses, as follows:
The beauty of this code is that all the references are from the superclass (i.e., programming at the interface level). You
could instantiate different subclass instance, and the code still works. You could extend your program easily by adding
in more subclasses, such as Circle, Square, etc, with ease.
Nonetheless, the above definition of Shape class poses a problem, if someone instantiate a Shape object and invoke
the getArea() from the Shape object, the program breaks.
This is because the Shape class is meant to provide a common interface to all its subclasses, which are supposed to
provide the actual implementation. We do not want anyone to instantiate a Shape instance. This problem can be
resolved by using the so-called abstract class.
For example, in the Shape class, we can declare three abstract methods getArea(), draw(), as follows:
20 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
Implementation of these methods is not possible in the Shape class, as the actual shape is not yet known. (How to
compute the area if the shape is not known?) Implementation of these abstract methods will be provided later once
the actual shape is known. These abstract methods cannot be invoked because they have no implementation.
Shape.java
abstract public class Shape {
// Private member variable
private String color;
// Constructor
public Shape (String color) {
this.color = color;
}
@Override
public String toString() {
return "Shape of color=\"" + color + "\"";
}
An abstract class is incomplete in its definition, since the implementation of its abstract methods is missing.
Therefore, an abstract class cannot be instantiated. In other words, you cannot create instances from an abstract
class (otherwise, you will have an incomplete instance with missing method's body).
To use an abstract class, you have to derive a subclass from the abstract class. In the derived subclass, you have to
override the abstract methods and provide implementation to all the abstract methods. The subclass derived is now
complete, and can be instantiated. (If a subclass does not provide implementation to all the abstract methods of the
superclass, the subclass remains abstract.)
21 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
This property of the abstract class solves our earlier problem. In other words, you can create instances of the
subclasses such as Triangle and Rectangle, and upcast them to Shape (so as to program and operate at the
interface level), but you cannot create instance of Shape, which avoid the pitfall that we have faced. For example,
In summary, an abstract class provides a template for further development. The purpose of an abstract class is to
provide a common interface (or protocol, or contract, or understanding, or naming convention) to all its subclasses. For
example, in the abstract class Shape, you can define abstract methods such as getArea() and draw(). No
implementation is possible because the actual shape is not known. However, by specifying the signature of the
abstract methods, all the subclasses are forced to use these methods' signature. The subclasses could provide the
proper implementations.
Coupled with polymorphism, you can upcast subclass instances to Shape, and program at the Shape level, i,e., program
at the interface. The separation of interface and implementation enables better software design, and ease in expansion.
For example, Shape defines a method called getArea(), which all the subclasses must provide the correct
implementation. You can ask for a getArea() from any subclasses of Shape, the correct area will be computed.
Furthermore, you application can be extended easily to accommodate new shapes (such as Circle or Square) by
deriving more subclasses.
Rule of Thumb: Program at the interface, not at the implementation. (That is, make references at the superclass;
substitute with subclass instances; and invoke methods defined in the superclass only.)
Notes:
An abstract method cannot be declared final, as final method cannot be overridden. An abstract method, on
the other hand, must be overridden in a descendent before it can be used.
An abstract method cannot be private (which generates a compilation error). This is because private method
are not visible to the subclass and thus cannot be overridden.
An interface is a contract for what the classes can do. It, however, does not specify how the classes should do it.
Interface Naming Convention: Use an adjective (typically ends with "able") consisting of one or more words.
Each word shall be initial capitalized (camel-case). For example, Serializable, Extenalizable, Movable, Clonable,
Runnable, etc.
22 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
Interface Moveable.java
public interface Movable {
// abstract methods to be implemented by the subclasses
public void moveUp();
public void moveDown();
public void moveLeft();
public void moveRight();
}
Similar to an abstract class, an interface cannot be instantiated; because it is incomplete (the abstract methods'
body is missing). To use an interface, again, you must derive subclasses and provide implementation to all the abstract
methods declared in the interface. The subclasses are now complete and can be instantiated.
MovablePoint.java
To derive subclasses from an interface, a new keyboard "implements" is to be used instead of "extends" for
deriving subclasses from an ordinary class or an abstract class. It is important to note that the subclass implementing
an interface need to override ALL the abstract methods defined in the interface; otherwise, the subclass cannot be
compiled. For example,
// Constructor
public MovablePoint(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public String toString() {
23 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
@Override
public void moveDown() {
y++;
}
@Override
public void moveLeft() {
x--;
}
@Override
public void moveRight() {
x++;
}
}
Other classes in the application can similarly implement the Movable interface and provide their own implementation
to the abstract methods defined in the interface Movable.
TestMovable.java
We can also upcast subclass instances to the Movable interface, via polymorphism, similar to an abstract class.
A subclass, however, can implement more than one interfaces. This is permitted in Java as an interface merely defines
the abstract methods without the actual implementations and less likely leads to inheriting conflicting properties from
multiple interfaces. In other words, Java indirectly supports multiple inheritances via implementing multiple interfaces.
For example,
public class Circle extends Shape implements Movable, Displayable { // One superclass but implement multiple in
.......
}
24 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
All methods in an interface shall be public and abstract (default). You cannot use other access modifier such as
private, protected and default, or modifiers such as static, final.
UML Notation: The UML notation uses a solid-line arrow linking the subclass to a concrete or abstract superclass,
and dashed-line arrow to an interface as illustrated. Abstract class and abstract method are shown in italics.
Secondly, Java does not support multiple inheritance (whereas C++ does). Multiple inheritance permits you to derive a
subclass from more than one direct superclass. This poses a problem if two direct superclasses have conflicting
implementations. (Which one to follow in the subclass?). However, multiple inheritance does have its place. Java does
this by permitting you to "implements" more than one interfaces (but you can only "extends" from a single superclass).
Since interfaces contain only abstract methods without actual implementation, no conflict can arise among the multiple
interfaces. (Interface can hold constants but is not recommended. If a subclass implements two interfaces with
25 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
6.7 Exercises
LINK TO EXERCISES ON POLYMORPHISM, ABSTRACT CLASSES AND INTERFACES
This, however, poses a new problem. The compiler cannot know at compile time precisely which piece of codes is going
to be executed at run-time (e.g., getArea() has different implementation for Rectangle and Triangle).
In the procedural language like C, the compiler generates a call to a specific function name, and the linkage editor
resolves this call to the absolute address of the code to be executed at run-time. This mechanism is called static binding
(or early binding).
To support polymorphism, object-oriented language uses a different mechanism called dynamic binding (or late-binding
or run-time binding). When a method is invoked, the code to be executed is only determined at run-time. During the
compilation, the compiler checks whether the method exists and performs type check on the arguments and return
type, but does not know which piece of codes to execute at run-time. When a message is sent to an object to invoke a
method, the object figures out which piece of codes to execute at run-time.
Although dynamic binding resolves the problem in supporting polymorphism, it poses another new problem. The
compiler is unable to check whether the type casting operator is safe. It can only be checked during runtime (which
throws a ClassCastException if the type check fails).
JDK 1.5 introduces a new feature called generics to tackle this issue. We shall discuss this problem and generics in
details in the later chapter.
Encapsulation refers to keeping the data and method inside a class such users do not access the data directly but via the
public methods. Tight encapsulation is desired, which can be achieved by declaring all the variable private, and
providing public getter and setter to the variables. The benefit is you have complete control on how the data is to be
read (e.g., in how format) and how to the data is to be changed (e.g., validation).
[TODO] Example: Time class with private variables hour (0-23), minute (0-59) and second (0-59); getters and setters
(throws IllegalArgumentException). The internal time could also be stored as the number of seconds since
midnight for ease of operation (information hiding).
Information Hiding: Another key benefit of tight encapsulation is information hiding, which means that the users are
not aware (and do not need to be aware) of how the data is stored internally.
The benefit of tight encapsulation out-weights the overhead needed in additional method calls.
Coupling refers to the degree to which one class relies on knowledge of the internals of another class. Tight coupling is
undesirable because if one class changes its internal representations, all the other tightly-coupled classes need to be
rewritten.
26 of 27 6/19/2013 8:09 PM
OOP Inheritance & Polymorphism - Java Programming Tutorial http://www.ntu.edu.sg/home/ehchua/programming/java/J3b_OOPInherita...
[TODO] Example: A class uses Time and relies on the variables hour, minute and second.
Clearly, Loose Coupling is often associated with tight encapsulation. For example, well-defined public method for
accessing the data, instead of directly access the data.
Cohesion refers to the degree to which a class or method resists being broken down into smaller pieces. High degree of
cohesion is desirable. Each class shall be designed to model a single entity with its focused set of responsibilities and
perform a collection of closely related tasks; and each method shall accomplish a single task. Low cohesion classes are
hard to maintain and re-use.
[TODO] Example of low cohesion: Book and Author in one class, or Car and Driver in one class.
Again, high cohesion is associated with loose coupling. This is because a highly cohesive class has fewer (or minimal)
interactions with other classes.
"has-a" relationship: In composition, a class contains references to other classes, which is known as "has-a" relationship.
You can use "is-a" and 'has-a" to test whether to design the classes using inheritance or composition.
Feedback, comments, corrections, and errata can be sent to Chua Hock-Chuan (ehchua@ntu.edu.sg) | HOME
27 of 27 6/19/2013 8:09 PM