You are on page 1of 48

CS 547

ADVANCED PROGRAMMING
(Lecture Note 2: OOP)
By
Isma’il Aliyu
Department of Mathematical Sciences
ATBU, Bauchi.
2020/2021 Session
Object Oriented Programming – OOP
• OOP is today’s key programming paradigm.
• The OOP paradigm enables programmers to modelled real life concepts or
entities.
• In object-oriented program,
• The program is divided into one or more units called classes.
• There are objects that interact with one another.
• The following concepts are fully utilised
• Encapsulation
• Inheritance
• Polymorphism
• Objects interact by sending messages. These messages are like procedure
or function calls;
• In Java, functions are called methods.
• Today, OOP is the dominant and preferred paradigm for software
development.
• significant software design methodologies are object oriented

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 2


CLASS
• A Java application (program) consists of one or more classes.
• In OOP, a class is the template or blueprint from which objects are
made.
• A class is a program unit that house the set of fields and methods
that perform computational the tasks.
– For example, a class that represents a bank account may contain
methods to deposit money, withdraw money and a method to inquire
the account’s current balance.
• Every object is created from a class.
– Therefore, object is defined as an instance of a class.
• You can create many objects or instances of a class. The process of
creating an instance is referred to as instantiation.
– The terms object and instance are often used interchangeably.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 3


Java class
• In Java, a class consist of the following members.
– Constructor
– Field
– Method
• The syntax of declaring a class is:
modifier class className {
// Constructors
// Methods
// Fields
}
• modifiers may be one more of the three keywords:
• public, final, abstract
• className is any valid identifier, and the body (enclosed in curly
brackets) is the sequence of declaration of variables (fields),
constructors and methods

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 4


Constructor
• A constructor is a special method whose purpose is to construct and
initialize objects.
• In Java, constructors are used to construct new objects (or instances) of
classes
• A class can have as many constructors but with different parameters.
• constructor
– accept parameters.
– always have the same name as class name
– Is invoked using new keyword
• Whenever you create an object of a class, you are calling a constructor of
that class.
• When a class is declared and no constructor is explicitly declared, by
default, Java automatically creates one for you.
• Such constructor is called default constructor. It sets all the instance fields to
their default values.
• A constructor that does not accept any parameter is called default constructor.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 5


Example – Constructor
• The syntax of declaring constructor is: • Example

modifier className(parameter-list) { public class Circle {


// constructor body
} public Circle() {
// statements
• modifier can be any of the three keywords: }
– public, public Circle(double radiu, String fillColor) {
– Protected
//statements
– private.
}
public Circle(double diameter) {
• The className is the name of the class in
which the constructor is declared. // statements
}
• parameter-list is a sequence of declaration }
of the parameters the constructor accepts.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 6


Creating objects of a class
• Creating/constructing object of a class simply means calling or
invoking one of class’s constructors.
• Constructors are invoked using the new as shown in the syntax
below.
• Syntax

className objectname = new className(parameter-list);

• Example, objects of Circle class can be constructed as follows:


//call the first constructor (default constructor)
Circle c1 = new Circle();
// call the second constructor
Circle c2 = new Circle(5.3, “Blue”);
// call the third constructor
Circle c3 = new Circle(12.5);

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 7


Fields
• A field is a data member of a class. The term variable and
fields are often used interchangeably.
• There are 2 types of fields in a class
1) Instance fields
2) Class fields
• Instance field
– Is a field that is bound or tie to a specific object (instance) of
the class. Every object of a class has different copy of those
fields. Instance field is not shared among objects of the same
class.
• Class field
– Is a field that is not bounded or tied to any object. A single class
field can be shared by many objects.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 8


Instance Field
• The syntax of declaring instance field is
– accessModifier type fieldname;
• Examples:
public boolean graduationStatus;
protected double balance;
private char grade;
• Any field within a class that is accessible to all methods
of the same class is an instance field provided that
static keyword is not used when declaring it.
• Methods too declared without using static keyword are
called instance methods. – Objects are used to invoke
them.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 9


Class Field
• Class fields are declared using static keyword.
• If you want a field to be shared by different objects, then you
declare the field as class or static field.
• Usually, class fields are used when there is need to have a one field
shared by many classes.
• The following are examples of class fields
private static int x;
public static final double y; // y is a class field and a constant as well
• Methods too can be declared as static. When methods are declared
as static, they can be called (invoked) without using an object.
• To access public static fields or static methods of a class from
another class does not require instantiating a class contain the
fields.
– Static fields and static methods of ClassA can be accessed from ClassB
without instantiating ClassA

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 10


Example – Fields
public class TF{
public class F{ public static void main(String [ ] args ){
public F(){ x = 0; y = 0;} F f1 = new F();
public F(int a, int b){ System.out.println(f1.getSum());
x = a; F f2 = new F(8,6);
y = b; System.out.println(f2.getSum());
} F f3 = new F(3,7.5);
public F(double k, double j){ System.out.println(f3.getSum());
x += k; }
y += j; }
} • Output
public double getSum( ){ 0
double z = x+y; 14.0
15.0
return z;
}
// instance fields • The output is different because instance
fields x are y are bounded to every object.
private double x = 2, y = 2.5; The values of x and y for f1 object are
} different from the values of x and y for f2 ,
and also different from that of f3 object

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 11


Characteristics of Object
• An object is defined as an instance of a class. Every object is created from
a class.
• An object has three characteristics
1) State
2) Identity
3) Behavior
• State
– An object of a class have specific values for its instance fields. The set of those
values is the current state of the object. Therefore, the values stored in the
instance fields represent the state of an object.
– Whenever a method is invoked on an object, the state of the object may
change.
– The state of an object may change over time, but not spontaneously.
– A change in the state of an object must be a consequence of method calls.
– If the object state changed without a method call on that object, then
encapsulation is violated.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 12


Characteristics of an object
• Identity
– The object’s identity means how an object can be distinguished from
other objects in terms of name and state. The state of an object does
not completely describe the object itself, because each object has a
distinct identity. For example, in an order-processing system, two
orders are distinct even if they request identical items. Notice that the
individual objects that are instances of a class always differ in their
identity and in most case differ in their state.
• Behaviour
– The behavior of an object (also known as its actions) is defined by
methods. To invoke a method on an object is to ask the object to
perform an action. For example, you may define a method named
getArea() in a circle class. if you use the circle objects to invoke the
getArea() method, you are simply asking the circle object to act.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 13


Method
• Method is a unit of a program that contain executable statements
to perform a task and optionally return value.
• Method help programmer to modularize a program by separating
its tasks into self-contained units
• We said that objects act. It is the methods that enable objects to
act.
• In Java, methods are the same as functions in other languages.
• Benefits for modularizing a program into method:
• It makes program development more manageable since the program is
constructed from smaller units.
• software reusability – using existing methods as building blocks to
create new programs. Once written, the statements in the method
bodies can be reused from several locations in a program.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 14


Method Declaration
• The syntax of method declaration is:
modifier returntype methodName(parameter-list) {
// method body
}
• modifier can be any of the keywords: public, protected, private,
static abstract, final, synchronized, native.
• returntype may be an object, string or any of the primitive data
types.
• methodName is any valid name.
• parameter-list is a sequence of declaration of the parameters that
the method accepts as arguments.
• Methods can accept one or more parameters.
• The parameters a method accepts are local to the method. That is,
they cannot be used outside it.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 15


Methods
• Accessor Methods
– These are methods allow access to instance fields.
Accesor methods only looks up the state of the
object and report it.
– The are typically the getX Methods
• Mutator Methods
– These are methods that change or modify
instance fields. Thus, they change the state of an
object.
– The are typically the setX methods
CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 16
Invoking Method
• To invoke method simply means to call it.
• The syntax differs depending on the type of
method your are invoking
– To invoke instance methods, you need to use an
object of the class in which the method is located. You
simply type the objectname followed by dot and then
methodname. That is,
objectname.methodname(parameters);
– To invoke static method, no need of using any object.
You simply type the classname followed by dot and
then the methodname. That is
classname.methodname(parameters)

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 17


Example – Method
// accessor method
public class Basket { public int getContent(){
// constructor return q;
public Basket(int x){ }
q = x; // instance field
} private int q = 0;
// mutator method
public void addToBasket (int qty ){ } // close Basket class
if(qty>0){
q += qty; public class TBasket{
System.out.println(qty + “ added.”); public static void main(String[ ] args){
} Basket b1 = new Basket();
} b1. addToBasket(110);
// mutator method b1.removeFromBasket(42);
public void removeFromBasket(int qnty){ System.out.println(“Basket contain”+ b1.getContent() );
if(q>= qnty){ System.out.println(“*************”);
q -= qnty; Basket b2 = new Basket(125);
System.out.println(qnty + “ removed.”); b2.removeFromBasket(15);
} System.out.println(“Basket contain”+ b2.getContent() );
} }
}

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 18


Example – Method
• The above example simulate a Basket here items can be added or
removed. The Basket class has 1 constructor, 3 methods, and 1
instance field.
• The TBasket class contain the main method in which the Basket
class is instantiated and its methods are invoked.
• The instance field q represents the available quantity of items in the
basket. It can be set via constructor, or calling addToBasket method.
• The b1 object set q by invoking addToBasket method while b2
object set q via constructor. Both b1 and b2 objects were used to
invoke methods of the Basket class.
– Since every object has its own state, the value returned by getContent
method will not be mixed up.
• There is only one Accessor method – that is, getContent. The rest
are mutator methods.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 19


Method Overloading
• Method overloading refers to
using the same name for many public int add(int a, int b, int c){
methods but with different int sum = a + b + c;
signatures.
• The signature of a method is the return sum;
list of parameters the method }
public double calculateArea(double length, double breadth) {
accepts. The following is an
example of method overloading. double area = length * breadth;
return area;
public class MethodOverLoading{ }
public double calculateArea(double base, int height) {
public int add(int a, int b{ double area = (base * height)/2;
int sum = a + b; return area;
return sum; }
}

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 20


Static method
• So far, the methods we have talked • Lets use Math class located in the
about operates on objects. In other java API to demonstrate the concept
word, object must be used in order to of static method.
call or invoke them. • Math class provides collection of
• However there are methods that do methods that enable you to perform
common mathematical calculations
not operate on objects. That is, they
so not need any object to be used in
calling them. These are called static // assign square root of 90 to n
methods double n = Math.sqrt(90);
• Static method is a method that do // assign 32, that is 2 power 5 (25) to m
not operate on objects. int m = Math.pow(2, 5);
• Static method are created by placing
the keyword static before the return • In each case, we did not use an
type in the method’s declaration. object of Math class before calling
• To call static method, we simply type sqrt or pow methods – why?
the class name followed by dot and • It is because they are static methods.
then name of the static method.
ClassName.methodName(arguments);

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 21


Static method
• You use static methods in two
situations: public class Employee{
1. When a method doesn’t need to public static String getEmployeeId() {
access the object’s state because
all needed parameters are return employeeId; // returns static field
supplied as explicit parameters }
(example: Math.sqrt()) // static field or class field
2. When a method only needs to private static String employeeId;
access static fields of the class.
}
• Because static methods don’t
operate on objects, you cannot
access instance fields from a • To call getEmpolyee method, you
static method. supply the name of the class
followed by dot and then the
• However, static methods can method‘s name:
access the static fields in their
class.
String n = Employee.getEmployeeId();
• The following is an example:

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 22


Passing and returning array from
method
• In the same way a method accepts and return single value or
object, a method can equally accepts and return an array.
• All that is required is to indicate the method’s parameters as array,
and the return type as array.
• The following method accepts an array, and return a new array such
that each element of new array is twice that of the passed array.

public int[] doubleArray(int[] array) {


int[] dArray = new int[array .length];
for (int i = 0, i = array.length - 1; i++){
dArray[i] = array[i] *2;
}
return dArray;
}

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 23


Exercises
• Write a method that accepts an array of string
type, extract and concatenate the 3rd, 5th and
last items of the array and return the resulting
string.
• Write a method that accepts array of numbers
and return the average of the numbers in the
array.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 24


OOP Concept – Encapsulation
• In OOP, Encapsulation means of binding together data (fields) and
operations (methods) to be performed on the data into a single unit and
ability of the unit to have full control on those fields and methods.
• In other words, Encapsulation is the programming mechanism that binds
together code and the data it manipulates, and that keeps both safe from
outside interference and misuse
• Encapsulation provides a mechanism of hiding or protecting some or all of
the fields and methods of a class from direct access and subsequent
modification. This is called Information hiding.
• The accessibility of the fields and methods of a class is usually controlled
by public, protected, or private access modifiers.
• Therefore, information hiding means protecting or hiding data (fields) and
methods of a class using access modifiers in order to prevent outside
interference.
• Outside interference here mean direct modification from somewhere.
• Information hiding is crucial to good software engineering.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 25


OOP Concept – Encapsulation
• We say that the Fields and method of a class are
encapsulated or bounded into an object. Once an
object of a class is created, the class’s methods
becomes accessible otherwise they are hidden.
• Encapsulation is the way to give the object its “black
box” behavior, which is the key to reuse and reliability.
• The key to making encapsulation work is to prevent
direct access to instance fields of a class from
somewhere, and allow methods within the class to
modify the fields.
• We have talked about encapsulation earlier, now lets
see examples that breaks encapsulation.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 26


OOP Concept – Encapsulation
• It is a good programming practice ensure that a class has full control
over it own fields and methods.
• Note that the term field here refers to instance fields, class fields or
local variables.
• Ideally, it is the methods of a class that should modify the fields
(data) of a class.
• That is why we have accessor and mutator methods.
• If a field can be modified from somewhere without using the
methods of a class, then encapsulation is violated!
• That is why it is always good to use private modifier for any important
and sensitive field of class, so that accessing such fields should only be
possible through the use of accessor methods.
• Breaking encapsulation means hijacking the control of class’s fields
by directly modifying them from outside the class.
• As we move on, we shall see examples that breaks encapsulation!

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 27


Example that breaks encapsulation
public class Encaps {
private String custormerId;
public double balance; public class TestEncaps {
/** Method that return the available balance */ public static void main(String[] args) {
public double getBalance(){ // create object of Encaps class
return balance; Encaps en = new Encaps();
} en.balance = 5300; // OK, but breaks encapsulation
/** Method to deposit amount */ en.deposit(2500); // legal way to change the balance field
public void deposit(double amt){ System.out.println("Available Bal:
if(amt > 0){ "+en.getBalance());
balance = balance + amt; }
}else{ }
System.out.println("Please enter
positive number");
}
}
}

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 28


Example that breaks encapsulation
• In the main method of TestEncaps class, the statement
en.balance = 5300;
• assigned value to balance (a public instance field in the Encaps class). The
above statement works. However, encapsulation is broken. Why?
• The statement clearly hijacked the control of the field from it class (Encaps
class). This contradict encapsulation which emphasis that a class should have
full control of all its fields and methods so as to prevent external interference.
• The only way to resolve the issue is to make balance field a private field.
That is, to change the access modifier from public to private.
• This is shows that you should be careful on the way in which you use access
modifiers.
• The best way to modify or alter the values of instance fields is to let the
methods of the class to do it. Thus the statement
en.deposit(2500);
• Invoked the deposit method which eventually modify the value of balance
field.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 29


OOP Concept – Inheritance
• Inheritance is the OOP concept which explains that the
functionalities (methods and fields) of one class can be
inherited by other classes. In other words, the properties of
one class can be made directly available to other classes.
• The class whose functionalities are being inherited is called
as superclass.
• The class that inherits the functionality of the superclass is
called subclass.
• Thus, functionality programmed into the earlier classes
may not need to be re-coded to be usable in the later
classes.
• Inheritance is promotes code reuse, hence reusability in OOP.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 30


OOP Concept – Inheritance
• For example, suppose we created a class called Shape as
super class, and Circle, Triangle, Rectangle classes as
subclasses, the Circle, Triangle, and Rectangle classes would
directly inherit all or some of the functionalities of the
shape class. – Reusability of code!
• We would only need to add only new data and
functionalities that are specific to the Circle, Triangle and
Rectangle classes.
• Inheritance enables you to define a general class and later
extend it to more specialized classes. Inheritance makes
program’s enhancement and maintenance much easier.
• The idea behind inheritance is that new classes can be
created to inherit the functionalities of the existing classes

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 31


Inheritance
• The UML class diagram that denote inheritance is:
superclass

subclass1 subclass2 subclass3

• Subclasses are defined by extending superclass using extends


keyword. The extends keyword indicates that you are making a new
class that derives from, or inherit functionalities of an existing class.
• The existing class is called the superclass, base class, or parent
class while the new class is called the subclass, derived class, or
child class.
• Whenever you see extends keyword in Java program, it denotes
inheritance.
• The terms superclass and subclass are commonly used by Java
programmers.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 32


Superclass and Subclass
• A superclass also referred to as a parent class or base class,
is a class whose methods and fields are being shared or
inherited.
• A subclass also called child class or derived class is a class
that extends the superclass and inherit its methods and
fields.
• A subclass inherits all accessible fields and methods from its
superclass and also, new data fields and methods can be added
to it.
• Inheritance promotes reusability of code
• methods and fields can be inherited from super classes. Thus,
no need to create (duplicate) the same methods or fields in sub
classes. All you need to do is to add new methods and fields to
suit your new class

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 33


What can be done in subclass?
• A subclass inherits all of the public and protected members of its
parent, no matter what package the subclass is in. The following can
be done in a subclass.
 You can declare new fields in the subclass that are not in the
superclass.
 You can declare new methods in the subclass that are not in the
superclass.
 You can write a subclass constructor that invokes the constructor of
the superclass, either implicitly or by using the keyword super.
 You can declare a field in the subclass with the same name as the one
in the superclass, thus hiding it (not recommended).
 You can write a new instance method in the subclass that has the
same signature as the one in the superclass, thus overriding it.
 You can write a new static method in the subclass that has the same
signature as the one in the superclass, thus hiding it.
• A subclass does not inherit the private members of its parent class.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 34


Example – Inheritance
• The following example demonstrate the concepts of
inheritance.
• Suppose you are to write program for a company in
which managers are treated differently from other
employees. Managers are, of course, just like
employees in many respects. Both employees and
managers are paid a salary. However, while employees
are expected to complete their assigned tasks in order
to be paid their salary, managers get additional
bonuses if they actually achieve target.
• How do you go about implementing this?
• This is the kind of situation that cries out for inheritance.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 35


Example – Inheritance
• We can create an Employee class consisting of
the fields and methods relevant to the general
employees.
• We then need to define a new class, Manager,
and add functionalities that are peculiar to the
manager, and extend the Employee class. More
abstractly, there is an obvious “is–a” relationship
between Manager and Employee. Every manager
is an employee: This “is–a” relationship is the
hallmark of inheritance.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 36


Example – Inheritance
public class Employee { public class Manager extends Employee {
public Employee(String n, double s, int y, int gl) { public Manager(String n, double s, int y, int gl) {
name = n; super(n, s, y, gl);
salary = s; this.bonus = 0;
yearStarted = y; }
gradeLevel = gl; public double getSalary() {
} double baseSalary = super.getSalary();
public String getName(){ return baseSalary + bonus;
return name; }
} public void setBonus(double b) {
double getSalary() { if(this.targetStatus == true)
return salary; bonus = b;
} }
public void raiseSalary(double byPercent) { public void setTargetStatus(boolean t){
double raise = salary * byPercent / 100; targetStatus = t
salary += raise; }
} private double bonus;
private String name; private boolean targetStatus;
private double salary; }
private int yearStarted;
private int gradeLevel;
}

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 37


Example – Inheritance
public class Test {
public static void main(String[ ] args) {
// construct a Manager object
Manager boss = new Manager("Carl Cracker", 80000, 1987, 12);
boss.setTargetStatus(true); // set target status true (that is, target achieved)
boss.setBonus(5000);
Employee[ ] staff = new Employee[3];
// fill the staff array with Manager and Employee objects
staff[0] = boss;
staff[1] = new Employee("Harry Hacker", 50000, 1989, 10);
staff[2] = new Employee("Tommy Tester", 40000, 1990, 9);
// print out information about all Employee objects
for (Employee e : staff)
System.out.println("name=" + e.getName() + ",salary=" + e.getSalary());
}
}

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 38


Example – inheritance
• The Manager class has a new fields to store the bonus, and the
target status. The class also has methods to set or modify these
fields.
• If you have a Manager object, you can simply invoke the setBonus
or setTargetStatus methods.
• if you have an Employee object, you cannot apply the setBonus
method—it is not among the methods that are defined in the
Employee class.
• You can equally use methods such as getName and raiseSalary with
Manager objects. Even though these methods are not explicitly
defined in the Manager class, they are automatically – inherited
from the Employee superclass.
• Similarly, the fields name, salary, yearStarted, and gradeLevel are
inherited from the superclass. Every Manager object has six fields:
name, salary, yearStarted, gradeLevel, bonus and targetStatus.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 39


Example – inheritance
• In the Employee class we have getSalary method which return base
salary. For the other employee, this is enough. However, for
managers, the getSalary method should return the sum of the base
salary and the bonus. So you need to supply a new method to
override the superclass method.
• In the getSalary method of the Manager class, we used super
keyword to invoke getSalary method of the Emloyee class. without
the super keyword, getSalary method of the Manager class will call
itself. The consequence is an infinite set of calls to the same
method, leading to a program crash.
• In the constructor of Manager class, we used super keyword again
to call the constructor of the Employee class.
• This is an example of chaining constructors, - calling one constructor
from within another

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 40


Example – inheritance
• The statement
super(String s, double s, int y, int gl);
means “call the constructor of the Employee superclass with n, s, y, and gl as
parameters.”
• Because the Manager constructor cannot access the private fields of the
Employee class, it must initialize them through a constructor of the
employee class.
• The call using super must be the first statement in the constructor for the
subclass.
• As you saw, a subclass can add fields, and it can add or override methods
of the superclass. However, inheritance can never take away any fields or
methods.
• In the Test class, we’ve created an array (staff) that hold three objects of
Employee type. The first object in that staff array is an object of Manager
class, while the other two objects are objects of Employee class.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 41


Example – inheritance
• We used loop to display the information about the staff
• What is remarkable is that the call e.getSalary() picks out the correct
getSalary method.
• Note that the declared type of e is Employee, but the actual type of
the object to which e refers can be either Employee or Manager.
• When e refers to an Employee object, then the call e.getSalary()
calls the getSalary method of the Employee class. However, when e
refers to a Manager object, then the getSalary method of the
Manager class is called instead. – Why?
• Answer: is because of polymorphism
• The fact that an object variable (such as the variable e) can refer to
multiple actual types is called polymorphism.
• Automatically selecting the appropriate method at runtime is called
dynamic binding.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 42


Important note
• In inheritance, the relationship between a subclass and a
superclass is: is-a relationship. In an is-a relationship, an
object of a subclass can also be treated as an object of its
superclass - e.g. a manager is an employee, a triangle is a
shape
• When defining a subclass by extending its superclass, you
only need to indicate the differences between the subclass
and the superclass. Factor out the most general (common)
methods and fields and place them into the superclass and
then place more specialized methods in the subclass.
• Unlike C++, Java does not allow multiple inheritance.
Instead, interface is used so that a subclass can inherit from
more than one superclass.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 43


OOP Concept – Polymorphism
• Polymorphism refers to the ability of something to take many
forms.
• In OOP, polymorphism refer to:
• The ability of objects to take many forms. That is, an object of a super
class can refer to the object of any of the subclasses.
• The ability of the same methods to be used in many form – method
overloading.
• Suppose we have a superclass called Shape and Triangle, Circle,
Rectangle, Trapezium as subclasses.
• Polymorphism means, an object of Shape class be used to refer to
any of the Triangle, Circle, Rectangle and Trapezium classes.
• Without polymorphism, we must individually create the objects of the
subclasses.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 44


Polymorphism
• The dictionary definition of polymorphism refers
• to a principle in biology in which an organism or species can have
many different forms or stages.
• This principle can also be applied to object-oriented programming
and languages like the Java language.
• In OOP, polymorphism refer to:
• The ability of objects to take many forms. That is, an object of a super
class can refer to the object of any of the subclass.
• The ability of the same methods to be used in many form – method
overloading.
• For example, you can assign a subclass object to a superclass
variable.
Employee e;
e = new Employee(. . .); // Employee object as expected
e = new Manager(. . .); // OK, Manager can be used as well

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 45


Polymorphism
• Suppose we have a super class called Animal, and Cow,
Sheep, Wolf, Cat as subclasses, the following
statements are valid and it is because of
polymorphism.
Animal a;
a = new Cow(. . .); // Cow is an animal
a = new Cat(. . .); // OK, Cat is an animal
a = new Animal(…..); //
• In the Java programming language, object variables are
polymorphic.
• A variable (object) of type Animal can refer to an object of
any subclass (such as Cow, Sheep, Wolf, Cat, and so on).

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 46


Polymorphism
• Lets use some code snippet from Test class in our last example to explain
something.
Manager boss = new Manager(. . .);
Employee[] staff = new Employee[3];
staff[0] = boss;
• In this case, the variables staff[0] and boss refer to the same object.
However, staff[0] is considered to be only an Employee object by the
compiler.
• You cannot assign a superclass reference to a subclass variable. For
example, it is not legal to make the assignment
Manager m = staff[0]; // ERROR
• The reason is clear: Not all employees are managers
• Similarly, the following assignments are invalid
Manager m = new Employee (……..); // ERROR
Cow cw = new Animal(….); // Error
• But the following is valid Employee m = new Manager(……);

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 47


Advantages of OOP
• With OOP, it is easier to model real life problems or
concepts.
• Systems modelled in objects are easier to maintain and
manipulate, because properties and methods can be altered for
a class without affecting the rest of the system.
• It promotes reuse of code.
• Once developed, a class or a method can be utilized as much as
possible. In addition, classes may inherit properties from more
super classes, so that the properties do not have to be
redefined for each subclass.
• Most of the latest software design methodologies such as
MVC (Model View Controller), and software documentation
tools like UML class diagram, sequence diagram are based
on OOP paradigm.

CS547_2020/2021_I. Aliyu. ATBU BAUCHI. 48

You might also like