Learning Module: Object-Oriented Programming (OOP101)
Learning Module: Object-Oriented Programming (OOP101)
LEARNING MODULE
IN
OBJECT-ORIENTED
PROGRAMMING
(OOP101)
MIDTERM
1ST SEMESTER A.Y. 2020-2021
FELIPE G. ANTE JR
CS Instructor
Page | 1
LEARNING TASK 6 (April 12-17,2021)
TOPIC
POLYMORPHISM
TOPIC OVERVIEW
Learning Task 6 will discuss the principles and methods of Polymorphism which is one
of the most important principle of Object-Oriented Programming Approach
ACTIVITY 6
-------------------------------------------------------------------------------------------------------------------------------
PRE-ASSESSMENT 6
-------------------------------------------------------------------------------------------------------------------------------
CONTENT DEVELOPMENT 6
I. POLYMORPHISM
Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic.
In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type
and for the class Object.
It is important to know that the only possible way to access an object is through a reference
variable. A reference variable can be of only one type. Once declared, the type of a reference
variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared
final. The type of the reference variable would determine the methods that it can invoke on the
object.
A reference variable can refer to any object of its declared type or any subtype of its
declared type. A reference variable can be declared as a class or interface type.
Example:
Let us look at an example.
Page | 2
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above examples −
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following
declarations are legal −
Example
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d, a, v, o refer to the same Deer object in the heap.
Virtual Methods
In this section, I will show you how the behavior of overridden methods in Java allows you
to take advantage of polymorphism when designing your classes.
We already have discussed method overriding, where a child class can override a method
in its parent. An overridden method is essentially hidden in the parent class, and is not invoked
unless the child class uses the super keyword within the overriding method.
Example
Page | 3
Now suppose we extend Employee class as follows −
/* File name : Salary.java */
public class Salary extends Employee {
private double salary; // Annual salary
Now, you study the following program carefully and try to determine its output −
Output
Constructing an Employee
Constructing an Employee
Page | 4
Here, we instantiate two Salary objects. One using a Salary reference s, and the other using an
Employee reference e.
While invoking s.mailCheck(), the compiler sees mailCheck() in the Salary class at compile
time, and the JVM invokes mailCheck() in the Salary class at run time.
mailCheck() on e is quite different because e is an Employee reference. When the compiler
sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.
Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At
run time, however, the JVM invokes mailCheck() in the Salary class.
This behavior is referred to as virtual method invocation, and these methods are referred to as
virtual methods. An overridden method is invoked at run time, no matter what data type the
reference is that was used in the source code at compile time.
-------------------------------------------------------------------------------------------------------------------------------
POST-ASSESSMENT 6
1. Given the program below. Show the output and identify the polymorphism part in this code.
(15 pts)
Animal.java
Horse.java
2. Based on your output in item 1 explain the code with Polymorphism method. (15 pts)
3. Create a program based on item 1. Create a new java files named it as Human.java and
Student.java. Show the output of your program. (20 pts)
------------------------------------------------------------------------------------------------------------------------------
TOPIC
INHERITANCE
TOPIC OVERVIEW
Page | 5
Learning Task 7-8 focuses on other important OOP method which is the Inheritance.
ACTIVITY 7-8
-----------------------------------------------------------------------------------------------------------------------------
PRE-ASSESSMENT 7-8
I. INHERITANCE
Inheritance can be defined as the process where one class acquires the properties (methods
and fields) of another. With the use of inheritance the information is made manageable in a
hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}
Sample Code
Following is an example demonstrating Java inheritance. In this example, you can observe two
classes namely Calculation and My_Calculation.
Using extends keyword, the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.
Example
class Calculation {
int z;
Page | 6
public void addition(int x, int y) {
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}
Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200
In the given program, when an object to My_Calculation class is created, a copy of the contents
of the superclass is made within it. That is why, using the object of the subclass you can access
the members of a superclass.
The Superclass reference variable can hold the subclass object, but using that variable you can
access only the members of the superclass, so to access the members of both classes it is
recommended to always create reference variable to the subclass.
If you consider the above program, you can instantiate the class as given below. But using the
superclass reference variable ( cal in this case) you cannot call the method multiplication(),
which belongs to the subclass My_Calculation.
Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
Note − 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.
Page | 7
It is used to differentiate the members of superclass from the members of subclass, if they have
same names.
Sample Code
This section provides you a program that demonstrates the usage of the super keyword.
In the given program, you have two classes namely Sub_class and Super_class, both have a
method named display() with different implementations, and a variable named num with
different values. We are invoking display() method of both classes and printing the value of the
variable num of both classes. Here you can observe that we have used super keyword to
differentiate the members of superclass from subclass.
class Super_class {
int num = 20;
Page | 8
Output
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20
class Superclass {
int age;
Superclass(int age) {
this.age = age;
}
IS-A Relationship
IS-A is a way of saying: This object is a type of that object. Let us see how the extends keyword
is used to achieve inheritance.
public class Animal {
}
Page | 9
Now, based on the above example, in Object-Oriented terms, the following are true −
Animal is the superclass of Mammal class.
Animal is the superclass of Reptile class.
Mammal and Reptile are subclasses of Animal class.
Dog is the subclass of both Mammal and Animal classes.
Now, if we consider the IS-A relationship, we can say −
Mammal IS-A Animal
Reptile IS-A Animal
Dog IS-A Mammal
Hence: Dog IS-A Animal as well
With the use of the extends keyword, the subclasses will be able to inherit all the properties of
the superclass except for the private properties of the superclass.
We can assure that Mammal is actually an Animal with the use of the instance operator.
class Animal {
}
Since we have a good understanding of the extends keyword, let us look into how
the implements keyword is used to get the IS-A relationship.
Generally, the implements keyword is used with classes to inherit the properties of an interface.
Interfaces can never be extended by a class.
Example
public interface Animal {
}
Page | 10
public class Dog extends Mammal {
HAS-A relationship
These relationships are mainly based on the usage. This determines whether a certain
class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.
Lets look into an example −
Example
public class Vehicle{}
public class Speed{}
Types of Inheritance
There are various types of inheritance as demonstrated below.
A very important fact to remember is that Java does not support multiple inheritance. This
means that a class cannot extend more than one class. Therefore following is illegal −
Example
public class extends Animal, Mammal{}
However, a class can implement one or more interfaces, which has helped Java get rid of the
impossibility of multiple inheritance.
Page | 11
POST-ASSESSMENT 7-8
NAME: ____________________________ COURSE & SECTION: ______ SCORE: ____
1. Create a program that computes the area of rectangle using Superclass constructor. Show
the output.
2. Complete the code in IS-A relationship with extends keyword. Show the output.
public class Monster {
}
-------------------------------------------------------------------------------------------------------------------------------
TOPICS
ENCAPSULATION
ABSTRACTION
TOPIC OVERVIEW
Learning Task 9-10 will discuss another set of OOP principles Encapsulation and
Abstraction
PRE-ASSESSMENT 9-10
Answer the following questions. Use a separate sheet of paper for your answer.
Page | 12
CONTENT DEVELOPMENT 9-10
I. ENCAPSULATION
Encapsulation is one of the four fundamental OOP concepts. The other three are
inheritance, polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting
on the data (methods) together as a single unit. In encapsulation, the variables of a class will be
hidden from other classes, and can be accessed only through the methods of their current
class. Therefore, it is also known as data hiding.
Example
Following is an example that demonstrates how to achieve Encapsulation in Java −
Page | 13
encap.setAge(20);
encap.setIdNum("12343ms");
System.out.print("Name : " + encap.getName() + " Age : " + encap.getAge());
}
}
Benefits of Encapsulation
The fields of a class can be made read-only or write-only.
A class can have total control over what is stored in its fields.
II. ABSTRACTION
As per dictionary, abstraction is the quality of dealing with ideas rather than events. For
example, when you consider the case of e-mail, complex details such as what happens as soon
as you send an e-mail, the protocol your e-mail server uses are hidden from the user. Therefore,
to send an e-mail you just need to type the content, mention the address of the receiver, and click
send.
Likewise in Object-oriented programming, abstraction is a process of hiding 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.
In Java, abstraction is achieved using Abstract classes and interfaces.
Abstract Class
A class which contains the abstract keyword in its declaration is known as 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.
Example
This section provides you an example of the abstract class. To create an abstract class, just use
the abstract keyword before the class keyword, in the class declaration.
Page | 14
public String toString() {
return name + " " + address + " " + number;
}
Now you can try to instantiate the Employee class in the following way −
Example
/* File name : Salary.java */
public class Salary extends Employee {
private double salary; // Annual salary
Page | 15
public void setSalary(double newSalary) {
if(newSalary >= 0.0) {
salary = newSalary;
}
}
Abstract Methods
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 semoi colon (;) at the end.
Following is an example of the abstract method.
Example
public abstract class Employee {
private String name;
private String address;
private int number;
Page | 16
Suppose Salary class inherits the Employee class, then it should implement
the computePay() method as shown below −
POST-ASSESSMENT 9-10
NAME: ____________________________ COURSE & SECTION: ______ SCORE: ____
Page | 17