1
INHERITANCE AND
POLYMORPHISM
Why Inheritance?
• 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.
Inheritance
• In the Java language, classes can be derived from other
classes, thereby inheriting fields and methods from those
classes.
• A class that is derived from another class is called a
subclass (also a derived class, extended class, or child
class).
• The class from which the subclass is derived is called a
superclass (also a base class or a parent class).
Inheritance
• Excepting Object, which has no superclass, every class
has one and only one direct superclass (single
inheritance).
• In the absence of any other explicit superclass, every
class is implicitly a subclass of Object.
• A subclass inherits all the members (fields, methods, and
nested classes) from its superclass.
• Constructors are not members, so they are not inherited
by subclasses, but the constructor of the superclass can
be invoked from the subclass.
GeometricObject Class
public class GeometricObject {
private String color;
private boolean filled;
protected GeometricObject() {
[Link] = "white";
}
protected GeometricObject(String color, boolean filled) {
[Link] = color;
[Link] = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
[Link] = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
[Link] = filled;
}
public void printInfo(){
[Link]("The Geometric is "+color);
}
}
Circle Class
public class Circle extends GeometricObject {
private double radius;
public Circle() {
this(1.0);
}
public Circle(double radius) {
this(radius, "white", false);
}
public Circle(double radius, String color, boolean filled) {
super(color, filled);
[Link] = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
[Link] = radius;
}
public double getArea() {
return radius*radius*[Link];
}
public double getPerimeter() {
return 2*radius*[Link];
}
}
TestInheritence Class
public class TestInheritance {
public static void main(String[] args){
[Link]("---Create a Circle c1---");
Circle c1 = new Circle();
if(c1 instanceof GeometricObject){
[Link]("c1 is a GeometricObject");}
if(c1 instanceof Circle){
[Link]("c1 is a Circle");}
if(c1 instanceof Object){
[Link]("c1 is an Object");}
[Link]("---Create a GeometricObject g1---");
if(g1 instanceof Circle){
[Link]("g1 is a Circle");}
if(g1 instanceof GeometricObject){
[Link]("g2 is a GeometricObject");}
[Link]("---Create a GeometricObject g2---");
GeometricObject g2 = (GeometricObject) new Circle();
if(g2 instanceof Circle){
[Link]("g2 is a Circle");}
if(g2 instanceof GeometricObject){
[Link]("g2 is a GeometricObject");}
}
}
Are superclass’s Constructor Inherited?
• No. They are not inherited.
• They are invoked explicitly or implicitly.
• Explicitly using the super keyword.
• A constructor is used to construct an instance of a class.
Unlike properties and methods, a superclass's
constructors are not inherited in the subclass. They can
only be invoked from the subclasses' constructors, using
the keyword super. If the keyword super is not explicitly
used, the superclass's no-arg constructor is automatically
invoked.
Superclass’s Constructor Is Always
Invoked
• A constructor may invoke an overloaded constructor or its
superclass’s constructor. If none of them is invoked
explicitly, the compiler puts super() as the first statement
in the constructor. For example,
public A() { public A() {
is equivalent to
} super();
}
public A(double d) { public A(double d) {
// some statements is equivalent to
super();
} // some statements
}
Using the Keyword super
• The keyword super refers to the superclass of the class in
which super appears. This keyword can be used in two
ways:
• To call a superclass constructor
• To call a superclass method
• CAUTION ! You must use the keyword super to call the
superclass constructor. Invoking a superclass
constructor’s name in a subclass causes a syntax error.
Java requires that the statement that uses the keyword
super appear first in the constructor.
Constructor Chaining
Constructing an instance of a class invokes all the superclasses’
constructors along the inheritance chain. This is called constructor
chaining.
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty(); 1. Start from the
}
main method
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty(); 2. Invoke Faculty
}
constructor
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
3. Invoke Employee’s no-
class Employee extends Person { arg constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
4. Invoke Employee(String)
class Employee extends Person { constructor
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
5. Invoke Person()
constructor
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
6. Execute println
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
7. Execute println
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
8. Execute println
[Link]("(1) Person's no-arg constructor is invoked");
}
}
Trace Execution
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Faculty's no-arg constructor is invoked");
}
}
class Employee extends Person {
public Employee() { 9. Execute println
this("(2) Invoke Employee’s overloaded constructor");
[Link]("(3) Employee's no-arg constructor is invoked");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
[Link]("(1) Person's no-arg constructor is invoked");
}
}
Declaring a Subclass and Call Superclass
Methods
• A subclass extends properties and methods from the
superclass. You can also:
• Add new properties
• Add new methods
• Override the methods of the superclass
• You can call superclass’ methods by using a super
keyword
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
/** Override the printInfo method defined in GeometricObject */
public void printInfo() {
[Link]();
[Link]( "It is a circle with radius of " + radius);
}
}
Overriding Methods in the Superclass
• 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.
• Like an instance method, a static method can be
inherited. However, a static method cannot be overridden.
If a static method defined in the superclass is redefined in
a subclass, the method defined in the superclass is
hidden.
Overriding vs. Overloading
public class Test { public class Test {
public static void main(String[] args) { public static void main(String[] args) {
A a = new A(); A a = new A();
a.p(10); a.p(10);
a.p(10.0); a.p(10.0);
} }
} }
class B { class B {
public void p(double i) { public void p(double i) {
[Link](i * 2); [Link](i * 2);
} }
} }
class A extends B { class A extends B {
// This method overrides the method in B // This method overloads the method in B
public void p(double i) { public void p(int i) {
[Link](i); [Link](i);
} }
} }
Polymorphism
public class PolymorphismDemo {
public static void main(String[] args) {
• An object of a subtype can be
m(new GraduateStudent());
m(new Student());
used wherever its supertype
m(new Person());
m(new Object());
value is required. This feature
}
is known as polymorphism.
public static void m(Object x) {
[Link]([Link]());
}
}
class GraduateStudent extends Student {
}
class Student extends Person {
public String toString() {
return "Student";
}
}
class Person extends Object {
public String toString() {
return "Person";
}
}
Casting Objects
• You have already used the casting operator to convert. In
the preceding section, the statement 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 m(new Student()); assigns the
object new Student() to a parameter of the Object type.
• This statement is equivalent to:
Object o = new Student(); // Implicit casting
m(o);
The statement Object o = new Student(), known as
implicit casting, is legal because an instance of
Student is automatically an instance of Object.
Casting from Superclass to Subclass
• Explicit casting must be used when casting an object from
a superclass to a subclass. This type of casting may not
always succeed.
Apple x = (Apple)fruit;
Orange x = (Orange)fruit;
The instanceof Operator
• Use the instanceof operator to test whether an object
is an instance of a class:
Object myObject = new Circle();
... // Some lines of code
/** Perform casting if myObject is an instance of
Circle */
if (myObject instanceof Circle) {
[Link]("The circle diameter is " +
((Circle)myObject).getDiameter());
...
}
The final Modifier
• The final class cannot be extended:
final class Math {
...
}
• The final variable is a constant:
final static double PI = 3.14159;
• The final method cannot be
overridden by its subclasses.
ABSTRACTION &
INTERFACE
Additional References:
[Link]
Why Abstraction?
• To hide the implementation details from the user, only the
functionality will be provided to the user. In other words,
the user will have the information on what the object does
instead of how it does it.
Abstract Class
• Abstract classes may or may not contain abstract
methods, i.e., methods without body ( public void get(); )
• But, if a class has at least one abstract method, then the
class must be declared abstract.
• If a class is declared abstract, it cannot be instantiated.
• To use an abstract class, you have to inherit it from
another class, provide implementations to the abstract
methods in it.
• If you inherit an abstract class, you have to provide
implementations to all the abstract methods in it.
Abstract Method
If you want a class to contain a particular method but you
want the actual implementation of that method to be
determined by child classes, you can declare the method in
the parent class as an abstract.
• abstract keyword is used to declare the method as
abstract.
• You have to place the abstract keyword before the
method name in the method declaration.
• An abstract method contains a method signature, but no
method body.
• Instead of curly braces, an abstract method will have a
semi colon (;) at the end.
Abstract Classes and Abstract Methods
GeometricObject Abstract class
-color: String
-filled: boolean
The # sign indicates -GeometricObject()
protected modifier -GeometricObject(color: string,
filled: boolean)
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
Abstract methods +getArea(): double
are italicized Methods getArea and getPerimeter are overridden in
+getPerimeter(): double Circle and Rectangle. Superclass methods are generally
omitted in the UML diagram for subclasses.
Circle Rectangle
-radius: double -width: double
+Circle() -height: double
+Circle(radius: double) +Rectangle()
+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
+getDiameter(): double +setWidthHeight(width: double, height:
double): void
+getHeight(): double
GeometricObject Class
public abstract class GeometricObject {
private String color;
private boolean filled;
public GeometricObject() {
[Link] = "blue";
}
public GeometricObject(String color, boolean filled) {
[Link] = color;
[Link] = filled;
}
public String getColor() {
return color;
}
public void setColor(String color) {
[Link] = color;
}
public boolean isFilled() {
return filled;
}
public void setFilled(boolean filled) {
[Link] = filled;
}
public abstract double getArea();
public abstract double getPerimeter();
}
Circle Class
public class Circle extends GeometricObject {
private double radius;
public Circle() {
this(1.0);
}
public Circle(double radius) {
this(radius, "white", true);
}
public Circle(double radius, String color, boolean filled) {
super(color, filled);
[Link] = radius;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
[Link] = radius;
}
public double getArea() {
return radius*radius*[Link];
}
public double getPerimeter() {
return 2*radius*[Link];
}
public double getDiameter(){
return 2*radius;
}
}
Rectangle Class
public class Rectangle extends GeometricObject {
private double width;
private double height;
public Rectangle() {
this(1.0, 1.0);
}
public Rectangle(double width, double height) {
this(width, height,"green", true);
}
public Rectangle(double width, double height, String color, boolean filled) {
super(color, filled);
[Link] = width; [Link] = height;
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}
public void setWidthHeight(double width, double height) {
[Link] = width; [Link] = height;
}
public double getArea() {
return width*height;
}
public double getPerimeter() {
return (2*width)+(2*height);
}
}
Interface
• An interface is a classlike construct that contains only
constants and abstract methods.
• In many ways, an interface is similar to an abstract class,
but the intent of an interface is to specify behavior for
objects.
Interface
• An interface is similar to a class in the following ways
• An interface can contain any number of methods.
• An interface is written in a file with a .java extension, with the name
of the interface matching the name of the file.
• The byte code of an interface appears in a .class file.
• Interfaces appear in packages, and their corresponding bytecode
file must be in a directory structure that matches the package
name.
Interface
• However, an interface is different from a class in several
ways, including
• You cannot instantiate an interface.
• An interface does not contain any constructors.
• All of the methods in an interface are abstract.
• An interface cannot contain instance fields. The only fields that can
appear in an interface must be declared both static and final.
• An interface is not extended by a class; it is implemented by a
class.
• An interface can extend multiple interfaces.
Define an Interface
• To distinguish an interface from a class, Java uses the
following syntax to define an interface:
public interface InterfaceName {
constant declarations;
method signatures;
}
• Example
public interface GeometricObjectInterface {
//describe how to calculate area
public double getArea();
}
Define an Interface
• The interface keyword is used to declare an interface.
Here is a simple example to declare an interface
• Interfaces have the following properties
• An interface is implicitly abstract. You do not need to use the
abstract keyword while declaring an interface.
• Each method in an interface is also implicitly abstract, so the
abstract keyword is not needed.
• Methods in an interface are implicitly public.
Implement an Interface
• A class uses the implements keyword to implement an
interface. The implements keyword appears in the class
declaration following the extends portion of the
declaration.
• Example
public class Circle2 implements GeometricObjectInterface
{
public double getArea(){
return radius*radius*[Link];
}
}
Implement an Interface
• When implementation interfaces, there are several rules −
• A class can implement more than one interface at a time.
• A class can extend only one class, but implement many interfaces.
• An interface can extend another interface, in a similar way as a
class can extend another class.
GeometricObjectInterface Class
public interface GeometricObjectInterface {
public double getArea();
public double getPerimeter();
}
Circle2 Class
public class Circle2 implements GeometricObjectInterface {
private double radius;
private final double PI = [Link];
private String color;
private boolean filled;
public String getColor(){
return color;
}
public void setColor(String color){
[Link] = color;
}
public boolean isFilled(){
return filled;
}
public void setFilled(boolean filled){
[Link] = filled;
}
public double getArea(){
return radius*radius*[Link];
}
public double getPerimeter(){
return 2*radius*[Link];
}
}
Interfaces vs. Abstract Classes
• In an interface, the data must be constants; an abstract
class can have all types of data.
• Each method in an interface has only a signature
without implementation; an abstract class can have
concrete methods.
Variables Constructors Methods
Abstract No restrictions Constructors are invoked by subclasses No restrictions.
class through constructor chaining. An abstract
class cannot be instantiated using the
new operator.
Interface All variables No constructors. An interface cannot be All methods must be
must be public instantiated using the new operator. public abstract
static final instance methods
Interfaces vs. Abstract Classes, cont.
• All classes share a single root, the Object class, but there is no
single root for interfaces. Like a class, an interface also defines a
type. A variable of an interface type can reference any instance of
the class that implements the interface. If a class extends an
interface, this interface plays the same role as a superclass. You
can use an interface as a data type and cast a variable of an
interface type to its subclass, and vice versa.
Interface1_2 Interface2_2
Interface1_1 Interface1 Interface2_1
Object Class1 Class2
Whether to use an interface or a class?
• Abstract classes and interfaces can both be used to
model common features. How do you decide whether to
use an interface or a class?
• In general, a strong is-a relationship that clearly describes a parent-
child relationship should be modeled using classes. For example, a
staff member is a person. So their relationship should be modeled
using class inheritance.
• A weak is-a relationship, also known as an is-kind-of relationship,
indicates that an object possesses a certain property. A weak is-a
relationship can be modeled using interfaces. For example, all
strings are comparable, so the String class implements the
Comparable interface.
UML
Basic UML for Class Diagram
- [Link]
- [Link]
- [Link]
composition/
- [Link]/boonrit/ood/class%[Link]
UML Diagrams
• UML stands for the Unified Modeling Language
• UML diagrams show relationships among classes and
objects
• A UML class diagram consists of one or more classes,
each with sections for the class name, attributes (data),
and operations (methods)
• Lines between classes represent associations
• A dotted arrow shows that one class uses the other (calls
its methods)
UML Symbol
• Class Class name
• Class name is defined at the
top of the class symbol GeometricObject
• Attributes is defined at the - color: String
- filled: boolean
second part together with their Class attribute
- GeometricObject()
types - GeometricObject(color: string,
filled: boolean)
• Constructors and methods are + getColor(): String
listed at the last part together + setColor(color: String): void
+ isFilled(): boolean
with their parameters and + setFilled(filled: boolean): void
return types
Constructors
• Sign denote the visibility and method
modifier
• - denotes private
• # denotes protected GeometricObject
Simplified
• + denotes public version
UML Symbol
GeometricObject
• Class
- color: String
Abstract class
• Abstract class and abstract - filled: boolean
methods are italicized. - GeometricObject()
- GeometricObject(color: string,
Sometimes you can see filled: boolean)
+ getColor(): String
stereotype of abstract. + setColor(color: String): void
• Interface is denoted by using + isFilled(): boolean
+ setFilled(filled: boolean): void
stereotype. + getArea(): double
+ getPerimeter(): double
• Static variable is denoted by
underlined text
<<interface>>
GeometricObjectInterface
Interface
+ COLOR: String {readOnly}
+ getArea(): double
+ getPerimeter(): double
UML Symbol
• Inheritance (A is a super class, B is a sub class)
Class A Class B
• Interface
<<interface>>
Class A Class B
• Dependency
Class A Class B
UML Symbol
• Association (Class A holds a class reference to Class B)
Class A Class B
• Aggregation
Class A Class B
• Composition
Class A Class B
UML Symbol
• Dependency
• Normally created when you receive a reference to a class as part of
a particular operation / method.
class Die {
public void Roll() { ... }
}
class Player
{
public void TakeTurn(Die die) /*Look, I’m dependent on Die and
it's Roll method to do my work*/
{
[Link](); ... }
}
UML Symbol
• Dependency
class Car { class Engine {
private String model; private String type;
private String manufacturer; Engine (String type) {
public Car (String model, String manufacturer){
[Link] = model; [Link] = type;
[Link] = manufacturer; }
} public String getType(){
public String getEngine ( Engine e) { return type;
return [Link](); }
} }
public String getModel(){
return model;
}
public String getManufacturer(){
return manufacturer;
}
}
UML Symbol
• Association
• Association defines the multiplicity between objects.
class Asset { ... }
class Player {
Asset asset;
public Player(Asset purchasedAsset) { ... } /*Set the asset via
Constructor or a setter*/
}
UML Symbol
• Association
UML Symbol
• Aggregation
• Aggregation is a special type of association. In aggregation, objects
have their own life cycle but there is an ownership. Whenever we
have “HAS-A” relationship between objects and ownership then it’s
a case of aggregation.
UML Symbol
• Composition
• Composition is a special case of aggregation. Composition is a
more restrictive form of aggregation. When the contained object in
“HAS-A” relationship can’t exist on it’s own, then it’s a case of
composition. For example, House has-a Room. Here room can’t
exist without house.