You are on page 1of 58

Advance Object Oriented Programming

STUDENT
Name:
Learning Module on [Course Code]
Student Number:
Program:
INSTRUCTIONS TO THE STUDENTS

Learning Module on [Course Code]


At CCC-DCE you learn through self-instructional modules, otherwise known as DCE Self-
Learning modules of DCEModL such as the one that you are now reading. It is significant that
you observe the following instructions:
1. Every student or course has a total of three (3) modules, each one might contain two or
more lessons. You must complete and satisfy the work prescribed by each module before
you can sit for the written examination that will determine if you pass or fail the course.
2. Make an effort to do some extra reading on any reference book on the subject (online or
offline) will do.
3. Test your own progress by performing the enrichment activities/application provided by
each lesson. Read the instructions very carefully and understand them well.
4. Consultation will be entertained by your professors through Facebook Messenger from
Monday to Friday (9-5pm). Strictly follow the schedule of consultations.
5. At the end of each module, perform the Assessment Test
6. Enrichment Activities/Application and Assessment Test with answers will be collected
periodically (sealed in long brown envelope signed across the flap and properly label it
with your name and year & section) and submit to the Office of the Director of the
Department of Computer Education (DCE), Baretto St., Brgy VII, Calamba City, Laguna,
for correction and grading. Corrected tests will be returned to you with the
corresponding grade or further instruction, if needed. While waiting, go on to the next
module and observe the same study procedure.
7. When you have accomplished all the modules of the course you are enrolled, you have to
come to CCC to take the written examination in person.

Learning Module on [Course Code]


LEARNING MODULE INFORMATION
I. Course Code CS 231
II. Course Title Advance Java Programming
III. Module Number 1
IV. Module Title Introduction to Object Oriented Programming (OOP)
V. Overview of the Module This module consists of 4 lessons, namely:
Lesson 1: OOP Fundamentals
Lesson 2: Encapsulation
Lesson 3: Inheritance
Lesson 4. Polymorphism

In this module you will learn the processes and terms related to
OOP and its importance in creating a system. Also discussed in
this module are the key concepts of OOP and the basic concept
of OOP application using encapsulation, inheritance and
polymorphism.

VI. Module Outcomes After studying this module on the basic concept of OOP, the
students shall be able to:
1) Narrate the important key points of the OOP
fundamentals
2) Determine the importance of encapsulation, inheritance
and polymorphism in software development.
3) Create an application to solve a particular business
requirement.

Learning Module on [Course Code]


1

Lesson 1. OOP Fundamentals

Lesson Objectives:
At the end of this lesson, you will be able to:
 Explain the Concept of OOP
 Explain the importance of OOP in software development
 Understand how to define a class and create objects of the class
 Create a program that implements the basic of OOP

Discussion:

What is OOP
Object-oriented programming (OOP) is a programming paradigm that uses objects and their interactions
to design applications and computer programs.

Procedural programming is about writing procedures or methods that perform operations on the data,
while object-oriented programming is about creating objects that contain both data and methods.

Object-oriented programming has several advantages over procedural programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code easier to
maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter development
time

Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition of code. You should
extract out the codes that are common for the application, and place them at a single place and reuse them
instead of repeating it.

Why Object Oriented Approach


A major factor in the invention of Object-Oriented approach is to remove some of the flaws encountered
with the procedural approach. In OOP, data is treated as a critical element and does not allow it to flow

Learning Module on [Course Code]


2

freely. It bounds data closely to the functions that operate on it and protects it from accidental
modification from outside functions. OOP allows decomposition of a problem into a number of entities
called objects and then builds data and functions around these objects. A major advantage of OOP is code
reusability.
Some important features of Object Oriented programming are as follows:
 Emphasis on data rather than procedure
 Programs are divided into Objects
 Data is hidden and cannot be accessed by external functions
 Objects can communicate with each other through functions
 New data and functions can be easily added whenever necessary
 Follows bottom-up approach

Key Concepts of OOP


 Objects
 Classes
 Data Abstraction and Encapsulation
 Inheritance
 Polymorphism

Objects
 Objects are the basic run-time entities in an object-oriented system. Programming problem is
analyzed in terms of objects and nature of communication between them. When a program is
executed, objects interact with each other by sending messages. Different objects can also interact
with each other without knowing the details of their data or code.

Classes 
 A class is a collection of objects of similar type. Once a class is defined, any number of objects can
be created which belong to that class.
 The terms class and object are sometimes used interchangeably, but in fact classes describe
the type of objects, while objects are usable instances of classes.
 So, the act of creating an object is called instantiation.
 Using the blueprint analogy, a class is a blueprint, and an object is a building made from that
blueprint.
 Classes are blueprints for Object.
 Objects are instance of classes.

Learning Module on [Course Code]


3

Illustration of Class and Objects

CLASSES OBJECTS
Mazda
Car Honda
Mitsubishi
Toyota

You can create as many objects as you want for the Car class
CLASSES OBJECTS
Bird
Animal Dog
Cat
Tiger

You can create as many objects as you want for the Animal class.
So, a class is a template for objects, and an object is an instance of a class.
When the individual objects are created, they inherit all the variables and methods from the class.

Tip. A class is not an object. class: The object is the actual component of programs, while the class
specifies how instances are created and how they behave.

Pillars of OOP
 Abstraction – is more of a concept and not a true programming technique. Purpose is simplifying
reality, focusing on what is important for a purpose.
 Encapsulation – hide complexity and implementation of the class. The data is exposed through
properties (getter/setter) and methods.
 Inheritance
 Polymorphism

Data Abstraction
 Abstraction refers to the act of representing essential features without including the background
details or explanations. Classes use the concept of abstraction and are defined as a list of abstract
attributes.

Learning Module on [Course Code]


4

 is the ability to generalize an object as a data type that has a specific set of characteristics and is able
to perform a set of actions.

 Object-oriented languages provide abstraction via classes. Classes define the properties and methods
of an object type.
Examples:
o You can create an abstraction of a dog with characteristics, such as color, height, and weight,
and actions such as run and bite.
o The characteristics are called properties, and the actions are called methods.
 A Recordset object is an abstract representation of a set of data.

Encapsulation
 Storing data and functions in a single unit (class) is encapsulation. Data cannot be accessible to the
outside world and only those functions which are stored in the class can access it.
 means that a group of related properties, methods, and other members are treated as a single unit or
object.

Inheritance
 Inheritance is the process by which objects can acquire the properties of objects of other class. In
OOP, inheritance provides reusability, like, adding additional features to an existing class without
modifying it. This is achieved by deriving a new class from the existing one. The new class will have
combined features of both the classes.
 describes the ability to create new classes based on an existing class.

Polymorphism 
 the ability to take more than one form. An operation may exhibit different behaviors in
different instances. The behavior depends on the data types used in the operation. Polymorphism is
extensively used in implementing Inheritance.
 means that you can have multiple classes that can be used interchangeably, even though each class
implements the same properties or methods in different ways.

Advantages of OOP
Object-Oriented Programming has the following advantages over conventional approaches:

o OOP provides a clear modular structure for programs which makes it good for defining abstract
data types where implementation details are hidden and the unit has a clearly defined interface.

Learning Module on [Course Code]


5

o OOP makes it easy to maintain and modify existing code as new objects can be created with
small differences to existing ones.
o OOP provides a good framework for code libraries where supplied software components can be
easily adapted and modified by the programmer. This is particularly useful for developing
graphical user interfaces.

Access Keywords
 Access keywords define the access to class members from the same class and from other classes.
 Access Modifiers are keywords used to specify the declared accessibility of a member of a type.

The most common access keywords are:

 Public: Allows access to the class member from any other class.
 Private: Allows access to the class member only in the same class.
 Protected: Allows access to the class member only within the same class and from inherited
classes.
 Internal: Allows access to the class member only in the same assembly.
 Protected internal: Allows access to the class member only within the same class, from inherited
classes, and other classes in the same assembly.
 Static: Indicates that the member can be called without first instantiating the class

Note. Class default access modifier = internal


Members of the class default modifier = private

Class Fundamentals
In java, the unit of programming is the class which objects are instantiated(created).
A class provides the definition for a particular type of object

Note. There is only one copy of a class definition in program, but there can be several objects that are
instances of that class

A class header has 3 parts


 An optional access modifier
 The keyword class
 Any legal identifier for classname

The body of a class consists of

Learning Module on [Course Code]


6

 Instance variables
 Methods
 which is enclosed with a set of curly braces {}
Tip. Class name should be in PascalCase (first letter in a word is capital (e.g. CustomerData,
OrderInformation).

Example:

Tip. If you put “public” as class header, your class file should be the same, otherwise it will be an error.

How to create objects


- the new operator is used to create an object of a class
- the new operator dynamically allocates memory for an object and return a reference to it. The
reference is the address in memory of the object allocated by new. This reference is then stored in the
variable.

To create an object using the class below.

//you can create multiple objects (student1, student2…) for the classStudent Information
StudentInformation student1 = new StudentInformation();
StudentInformation student2 = new StudentInformation();

Student1.name="Test";

Learning Module on [Course Code]


7

Student2.name="Test2";
//call the method
Student1.display();
Student2.display();

- here student is called the object of the class


- it is important to understand that the new allocates memory for an object during run-time. The
advantage is that your program can create as many or as few objects as it needs during the execution
of your program
- once you have created the object, you never have to worry about destroying it since objects are
automatically garbage collected in Java.

Example
Follow steps below
1. Create a project and name it IntroToOOP
2. In the project window, create a class and named it StudentInformation as shown below

Learning Module on [Course Code]


8

3. In the StudentInformation.java, type the code as shown in red box below

Note. if the class access modifier is public, the filename should be the same. So here, the name of the
class is StudentInformation so the java filename should be the same, StudentInformation, otherwise it
is an ERROR.

4. Create a JFrame to implement the StudentInformation class. JFrame is your User Interface (UI).
Follow steps a, b and c.

a.

Learning Module on [Course Code]


9

b.

c. After creating the StudentInformation_UI, design the JFrame as below

Learning Module on [Course Code]


10

d. With the user interface as shown in c, the user will enter username and password. When the user
click the Display button, it will display the name and user entered both in the label and in the
console.

The code of display button is shown red box below.

When you run the code and click display button you should see the output in red box as below.

Note. if you cannot see the output as shown in the output red box, go to the output window as shown
below

Learning Module on [Course Code]


11

Notice in the project, we have two classes, separating the logic (StudentInformation) and the
implementation or User Interface(StudentInformation_UI)

In reality, you can combine the logic and implementation in one class just like below and the output is the
same.

Inside the StudentInformation_UI.java file, you can now see two classes, StudentInformation(the logic)
and the StudentInformation_UI (the implementation or User Interface).

Learning Module on [Course Code]


12

Tip. Just make sure that only one class has public access modifier.

Constructor
 a constructor initializes an object immediately upon creation. Once defined, the constructor is
automatically called immediately after the object is created, before the new operator completes.

Constructor are identified by the following rules


 the method name must exactly match the classname
 there must not be a return type declared for the method

example.

class test {
public test() { }
}
public test(int x) {
}

Note. every class has at least one constructor. If you do not write a constructor, Java provides one for you.
The default constructor takes no arguments and has an empty body.

Example:
Using the same UI interface, modify the class StudentInformation where it will initialize the instance
variables of name to “Rick” and surname to “Ang”

Modify your code as shown in red box below. Notice that we also modify the code of the display button.

Learning Module on [Course Code]


13

When you run the code, the output is shown below. Notice that when you clicked the Display button, the
program output is Rick Ang, though the user did not input anything in the text boxes. This is because of
the work of constructor, which initializes the class automatically.

Constructor with Parameters


Constructors can also take parameters, which is used to initialize attributes.
Using same UI interface, modify the class StudentInformation where it will initialize the instance
variables of name to “Rick” and surname to “Ang” in the class constructor using constructor parameters

Solution:

Learning Module on [Course Code]


14

As you can see in the example, class StudentInformation has a method named StudentInformation with
two formal parameters String n and String s. So this is called the constructor with formal parameters.
When you create object of the StudentInformation class you should pass two arguments or actual
parameters.

Summary
In this module, you learned the importance of OOP in creating a real-world application. You also learned
that in order to understand OOP, you need to understand the following concepts:
• Objects
• Classes
• Data Abstraction and Encapsulation
• Polymorphism
• Inheritance

Also, in this module you learned the basic structure of java application, how to declare objects, how
variables and methods are worked under classes, as well as the use of constructor. You also learned where
objects came from, and you learned that a class is a set of plans, or in short, a blueprint, that can be used
to construct objects. You learned that a Java object is an instance of a class.

Lesson 2. Encapsulation

Lesson Objectives:
At the end of this lesson, you will be able to:

Learning Module on [Course Code]


15

 Explain the concept of encapsulation


 Explain the importance of encapsulation in software development
 Understand when and when to use access modifiers in designing a class.
 Create a program that implements the concept of encapsulation

Discussion:

Encapsulation
 Encapsulation simply means binding object state(fields) and behavior(methods) together. If you are
creating class, you are doing encapsulation
 The whole idea behind encapsulation is to hide the implementation details from users. If a data
member is private it means it can only be accessed within the same class. No outside class can access
private data member (variable) of other class.
 Encapsulation is also known as data hiding

Data Hiding
 Data hiding is referred to as encapsulation
 Distinguishes the outside interface to the class from its implementation
 Hides the implementation details of the class
 Forces the user to use an interface to access data
 Makes the code much more maintainable

Advantages of encapsulation
 It improves maintainability and flexibility and re-usability
 The fields can be made read-only (If we don’t define setter methods in the class) or write-only (If we
don’t define the getter methods in the class).
 User would not be knowing what is going on behind the scene. They would only be knowing that to
update a field call set method and to read a field call get method but what these set and get methods
are doing is purely hidden from them.

How to implement encapsulation in java:


1. Make the instance variables private so that they cannot be accessed directly from outside the class.
You can only set and get values of these variables through the methods of the class.
2. Have getter and setter methods in the class to set and get the values of the fields.
3. The get method returns the variable value, and the set method sets the value.

Learning Module on [Course Code]


16

4. Syntax for both is that they start with either get or set, followed by the name of the variable, with the
first letter in upper case:

Access Keywords – a review


 Access keywords define the access to class members from the same class and from other classes.
 Access Modifiers are keywords used to specify the declared accessibility of a member of a type.

The most common access keywords are:

 Public: Allows access to the class member from any other class.
 Private: Allows access to the class member only in the same class.
 Protected: Allows access to the class member only within the same class and from inherited
classes.
 Internal: Allows access to the class member only in the same assembly.
 Protected internal: Allows access to the class member only within the same class, from inherited
classes, and other classes in the same assembly.
 Static: Indicates that the member can be called without first instantiating the class

Note. Class default access modifier = internal


Members of the class default modifier = private

Tip. "Accessor" and "Mutator" are just fancy names for a getter and a setter. A getter, "Accessor", returns
a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value. ... If you
instantiate this class the default values for these variables will be meaningless

Example 1
Step 1. Create a project call Encapsulation
Step 2. In the Encapsulation project, create a class called EncapsulationDemo as shown below

Learning Module on [Course Code]


17

The public setXXX() and getXXX() methods are the access points of the instance variables of the
EncapsulationDemo class. Normally, these methods are referred as getters and setters. Therefore, any
class that wants to access the variables should access them through these getters and setters.

Step 3. Create a JFrame,name it EncapsulationDemo_UI to test the EncapsulationDemo as shown


below

Learning Module on [Course Code]


18

Step 4. In the Proceed button, type the code below

EncapsulationDemo demo = new EncapsulationDemo();


demo.setEmpAge(Byte.parseByte(txtAge.getText()));
demo.setEmpName(txtName.getText());
//display the data
JOptionPane.showMessageDialog(null,
"Your name is : " + demo.getEmpName() + "\n" +
"Your age is : "+ demo.getEmpAge());

Step 5. Run the program. In the name textbox type Rommel and in the age textbox type 10. When
you click the Display button, you should see a message box display the data you typed in. as below.

Now, if you want to validate the age, let say 1 to 100 only. You need to modify the setter for this field.
Lets modify the EncapsulatonDemo class as shown below

Learning Module on [Course Code]


19

Here, we put a condition that we only accept 1 to 100, otherwise it will show error message.
So when you run the program and enter 500 in the age text box, it will show an error as below.

This is one of the power or encapsulation. You can validate the value of the data entered before it will
send to the designated variable.

Example 2
Modify the EncapsulationDemo class by commenting the setEmpName method as below

Learning Module on [Course Code]


20

What did you notice? The EncapsulationDemo_UI.java icon change as below, which means there is an
error in this class that implementing the EncapsulationDemo.

What is the reason? You are accessing setEmpName that is not available in EncapsulationDemo class.
Since the data empName is declared private in this class, no way you can enter the data. This is called
Read-only Class

Read-Only class
 A Java class which has only getter methods.  
public class Student{  
//
//private data member  
private String college="AKG";  
//getter method for college  
public String getCollege(){  
return college;  
}  }  

Learning Module on [Course Code]


21

Now, you can't change the value of the college data member which is "AKG".
s.setCollege("KITE");//will render compile time error  

Write-Only class
 A Java class which has only setter methods.  

public class Student{  
//private data member  

private String college;  
//getter method for college  

public void setCollege(String college){  
this.college=college;  
}  
}  

Now, you can't get the value of the college, you can only change the value of college data member.

System.out.println(s.getCollege());//Compile Time Error, because there is no such method  
System.out.println(s.college);//Compile Time Error, because the college data member is private.   
//So, it can't be accessed from outside the class  

The THIS keyword

Keyword THIS is a reference variable in Java that refers to the current object.

The various usages of 'THIS' keyword in Java are as follows:

 It can be used to refer instance variable of current class


 It can be used to invoke or initiate current class constructor
 It can be passed as an argument in the method call
 It can be passed as argument in the constructor call
 It can be used to return the current class instance

Learning Module on [Course Code]


22

Example
Step 1. In the current project, create Account class. Type the code in red box as shown below

Step 2. Create a JFrame form and name it AccounUI as shown below

Learning Module on [Course Code]


23

Step 3. In the Display button, type the code below

Account acct = new Account();


int n1 = Integer.parseInt(txtAccount1.getText());
int n2 = Integer.parseInt(txtAccount2.getText());
acct.setData(n1, n2);
acct.showData();

Step 4. Run the JFrame form. Enter data and click the Display button. You should see the output as
shown below

What did you notice in the Message Box? If you say the message box is not displaying the data
entered then you are right. it should display 19 and 20 respectively.

To fix this, replace the Account class code (SetData function) as shown in red box below.

Learning Module on [Course Code]


24

Run the program again and do the same process. Your output should be valid now.

Summary

In this module, you learned the concept of one of the pillars of OOP, which is encapsulation.
Encapsulation is also known as data hiding.

You also learned the concept of data hiding and how to implement by

 Making the instance variable private


 Have getter and setter methods in the class to set and get the values of the fields.

You also learned what is read-only class, write-only class and the use of this keyword. By using
encapsulation, you can leverage the benefits of abstraction, implementation hiding, and responsibility in
your application. With abstraction, you can write objects that are usable in a number of situations. If you
properly hide your object’s implementation, you can make any enhancements to your code without
affecting other, which is important in designing java application.

Learning Module on [Course Code]


25

Lesson 3. Inheritance

Lesson Objectives:
At the end of this lesson, you will be able to:
 Explain the concept of Inheritance
 Explain the importance of inheritance in software development
 Explain the difference between parent/base class and derived/child class
 Explain the difference between has-a and is-a relationship
 Create a program that implements the concept of inheritance

Discussion:

Inheritance
The process by which one class acquires the properties (data members) and functionalities(methods) of
another class is called inheritance. The aim of inheritance is to provide the reusability of code so that a
class has to write only the unique features and rest of the common properties and functionalities can be
extended from the another class.

Child Class:
The class that extends the features of another class is known as child class, sub class or derived class.

Parent Class:
The class whose properties and functionalities are used(inherited) by another class is known as parent
class, super class or Base class.

Note. Inheritance is a process of defining a new class based on an existing class by extending its common
data members and methods.
Inheritance allows us to reuse of code, it improves reusability in your java application.
Note: The biggest advantage of Inheritance is that the code that is already present in base class need not
be rewritten in the child class.

Learning Module on [Course Code]


26

This means that the data members(instance variables) and methods of the parent class can be used in the
child class as.
 to inherit a class, use the extends keyword

Consider the code below.

class Animal{
public String eat() {
return "eat";
}
public String sleep() {
return "sleep";
}
}
class Dog extends Animal {
public String Bark() {
return "Dog bark";
} }

Here, we have inherited a subclass Dog from superclass Animal. The Dog class inherits the methods eat()
and sleep() from the Animal class.
Hence, objects of the Dog class can access the members of both the Dog class and the Animal class.

Learning Module on [Course Code]


27

Lets try to create a project to see how this works.


Step 1. Create a project name Inheritance
Step 2. In the project, create a class name Animal. In the Animal class, type the code below

class Animal {
public String eat() {
return "eat";
}
public String sleep() {
return "sleep";
}
}
class Dog extends Animal{
public String Bark() {
return "Dog bark";
}}

Your project should be the same as below

Learning Module on [Course Code]


28

Step 3. Create a JFrame and name it AnimalUI. Design the form as shown below.

Step 4. In the Display button, type the code below

Dog d = new Dog();


lblDisplay.setText(d.eat() + " " + d.sleep() + " " + d.Bark());

Step 5. Run the program, and click the Display button. The output is shown in the red box

Notice that the output display eat, sleep and Dog bark, even though the Dog class only have one method
which is bark. The reason is because Dog class inherited the methods of Animal class, which means the
Dog class can access the eat and sleep method of Animal class.

Learning Module on [Course Code]


29

Another Example
In the current project, create a new JFrame called Ex2. In the JFrame, follow the design as below

In the JFrame code source, type the following in red box. Note that we can combine multiple classes in
one file, provided that only one class has public access modifier

Note. class Test is inside the JFrame code. This is valid, provided that the class does not have public
access modifier.

When you run the program and click the Proceed Button, the output in the text box is 30.

This is because Test1 class inherits the num1 variable of class Test giving Test1 class two variables which
are num1 and num2.

Learning Module on [Course Code]


30

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{


}
public class Mammal extends Animal{
}
public class Reptile extends Animal{
}
public class Dog extends Mammal {
}

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.

Learning Module on [Course Code]


31

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 −

public class Vehicle { }


public class Speed { }

public class Van extends Vehicle {


private Speed sp;
}

This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the
entire code that belongs to speed inside the Van class, which makes it possible to reuse the Speed class in
multiple applications.

In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To
achieve this, the Van class hides the implementation details from the users of the Van class. So, basically
what happens is the users would ask the Van class to do a certain action and the Van class will either do
the work by itself or ask another class to perform the action.

Types of Inheritance

Learning Module on [Course Code]


32

The super keyword


super is used in a class to refer to the member variables of its superclass.

The super keyword is similar to this keyword. Following are the scenarios where the super keyword is
used.
 It is used to differentiate the members of superclass from the members of subclass, if they have
same names.
 It is used to invoke the superclass constructor from subclass.

Example
Step 1. In the current project, create SuperExample class. Type the code in red box as shown below.

Step 2. Create a JFrame form and name it SuperExampleUI. Design the form as below

Learning Module on [Course Code]


33

Step 3. In the Super Example button, type the code below.

DerivedClass o = new DerivedClass();


o.printColor();

Step 4. Run the JFrame form and click the button. You should see two message boxes as below

The final Keyword


If you don't want other classes to inherit from a class, use the final keyword:
If you try to access a final class, Java will generate an error:

final class Vehicle {


...
}
class Car extends Vehicle {
...
}

The output will be something like this:


Car.java:8: error: cannot inherit from final Vehicle

class Car extends Vehicle {


                  ^
1 error)

Learning Module on [Course Code]


34

Summary
In this module, you learned the concept of one of the pillars of OOP, which is inheritance. You should
now understand the basic mechanics of inheritance and illustrates the importance of considering “Is-A”
and “Has-A” relationship while forming inheritance hierarchies.

You also learned the concept of parent or base class as well as child or derived class and how their
application. You should now be familiar with the types of inheritance, the use of super keyword as well as
the use of final when doing inheritance.

Finally, inheritance only makes sense from the relational or “Is-a” point of view. If two objects are not
related by type, they should not inherit.

Learning Module on [Course Code]


35

Lesson 4. Polymorphism

Lesson Objectives:
At the end of this lesson, you will be able to:
 Explain the concept of polymorphism
 Explain the importance of polymorphism in software development
 Explain what is method overloading and method overriding
 Create a program that implements the concept of polymorphism

Discussion:

Polymorphism
 is a concept by which we can perform a single action in different ways. Polymorphism is derived
from 2 Greek words: poly and morphs. The word "poly" means many and "morphs" means forms.
So polymorphism means many forms.
 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.

Methods Overloading

Learning Module on [Course Code]


36

 In Java, it is possible to define two or more methods within the same class that share name, as
long as their parameter declarations are different. When this is the case, the methods are said to
be overloaded and the process is referred to as method overloading.
 Method overloading is one of the ways that Java implements polymorphism.
With method overloading, multiple methods can have the same name with different parameters:

Example
int MyMethod(int a)
float MyMethod(float b)
double MyMethod(String x, double y)

Static Polymorphism:
In Java, static polymorphism is achieved through method overloading. Method overloading means there
are several methods present in a class having the same name but different types/order/number of
parameters.

At compile time, Java knows which method to invoke by checking the method signatures. So, this is
called compile time polymorphism or static binding. The concept will be clear from the following
example:

2 rules apply to overload methods


 arguments list must differ
 return types can be different

When an overload method is invoked, Java uses the type and/or number of arguments as its guide to
determine which versions of the overloaded method to actually call. Therefore the overload methods must
differ in the type and/or number of arguments

Example (different type of arguments)

public void print(int a) { }


public void print(String a) { }
public void print(double a) { }

Learning Module on [Course Code]


37

Example (different number of arguments)

public void print(int a, int b) { }


public void print(int a, String x) { }
public void print(String a, int b) { }
public void print(double a, int x, int y) { }

Example:
Step 1. Create a project and name it Polymorphism
Step 2. In the project, create a class and name it Poly. Type the code in the red box as shown below.

Notice that we have two methods wit the same name (print). But the parameter is different when it comes
to data type. This is method overloading.
Step 3. Create a JFrame form, name it PolyUI. Design the form as shown below.

Learning Module on [Course Code]


38

Step 4. In the button, type the code below

Poly p = new Poly();


p.print("This is String");
p.print(100);

Step 5. Run the JFrame and click the button. You should see two messageboxes as shown below

Method Overloading and Type Promotion


When a data type of smaller size is promoted to the data type of bigger size than this is called type
promotion, for example: byte data type can be promoted to short, a short data type can be promoted to int,
long, double etc.

Learning Module on [Course Code]


39

What it has to do with method overloading?


Well, it is very important to understand type promotion else you will think that the program will throw
compilation error but in fact that program will run fine because of type promotion.

Lets take an example


Step 1. In the current Polymorphism project, create a class and named it Demo. Type the code in the red
box as shown below.

Step 2. Create a JFrame form to test the Demo class shown below.

Step 3. In the button, type the code below

Demo obj = new Demo();


obj.disp(100, 20.67f);

Step 4. Run the JFrame and click the button. You should see a message box as below

Learning Module on [Course Code]


40

As you can see, we pass the float value while calling the disp() method but it got promoted to the double
type as there wasn’t any method with argument list as (int, float)

But this type promotion doesn’t always happen, lets see another example:

Modify the Demo class and add the code in yellow below

import javax.swing.JOptionPane;
class Demo {
void disp(int a, double b) {
JOptionPane.showMessageDialog(null, "Method A");
}
void disp(int a, double b, double c) {
JOptionPane.showMessageDialog(null, "Method B");
}
void disp(int a, float b) {
JOptionPane.showMessageDialog(null, "Method C");
}
}

So when you run the program again, the output is

Learning Module on [Course Code]


41

As you see that this time type promotion didn’t happen because there was a method with matching
argument type.

Type Promotion table:


The data type on the left side can be promoted to the any of the data type present in the right side of it.

byte → short → int → long


short → int → long
int → long → float → double
float → double
long → float → double

Dynamic Polymorphism:
Suppose a sub class overrides a particular method of the super class. Let’s say, in the program we create
an object of the subclass and assign it to the super class reference. Now, if we call the overridden method
on the super class reference then the sub class version of the method will be called.

Example.
Step 1. In the current project, create a class and name it as Vehicle. Type the code in red box as shown
below.

Learning Module on [Course Code]


42

Step 2. Create a JFrame form and name it as VehicleUI as shown below

Step 3. In the button type the code below

Vehicle vh = new Vehicle();


vh.move(); // prints MotorBike can move and accelerate too!!

MotorBike mb = new MotorBike();


mb.move(); // prints Vehicles can move!!

Learning Module on [Course Code]


43

Step 4. Run the JFrame. When you click the button you should see the output as below.

In the above code implementation you can see that MotorBike class have two same methods, move
because MotorBike class extends Vehicle class, but the application will execute the method define in the
class itself.

Lets try another way, modify the UI button as below

Vehicle vh = new MotorBike();

vh.move(); // prints MotorBike can move and accelerate too!!


vh = new Vehicle();

Learning Module on [Course Code]


44

vh.move(); // prints Vehicles can move!!

When you run the UI program, it will show as below

It should be noted that in the first call to move(), the reference type is Vehicle and the object being
referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to determine which
object is actually being pointed to by the reference. In this case, the object is of the class MotorBike. So,
the move() method of MotorBike class will be called. In the second call to move(), the object is of the
class Vehicle. So, the move() method of Vehicle will be called.

Tip: As the method to call is determined at runtime, this is called dynamic binding or late binding.

Another example, think of a superclass called Animal that has a method called animalSound(). Subclasses


of Animals could be Pigs, Cats, Dogs, Birds - And they also have their own implementation of an animal
sound (the pig oinks, and the cat meows, etc.):

Step 1. In the current project, create a class Animal and type the code in red box below.

Learning Module on [Course Code]


45

Step 2. To test the class, create a JFrame, name it AnimalUI with three labels, three text boxes and one
button as shown below.

Note. modify the textboxes editable properties to false by unchecking the checkbox as shown below.
When you uncheck the checkbox, it means that the text box is read only, meaning user cannot input the
data. You can use label also instead of text box.

Learning Module on [Course Code]


46

Step 3. In the proceed button, type the code below.

Animal myAnimal = new Animal(); // Create Animal object


Animal myPig = new Pig(); // Create a Pig object
Animal myDog = new Dog(); // Create a Dog object

//display the sounds of each objects


txtAnimalSound.setText(myAnimal.animalSound());
txtPigSound.setText(myPig.animalSound());
txtDogSound.setText(myDog.animalSound());

Step 4. Run the JFrame program and click the proceed button. You should see the output as shown below.

Learning Module on [Course Code]


47

Overloading constructors
 in addition to overloading methods, you can overload constructors too. The proper overloaded
methods is called based upon the parameters specified when the new is created.

Example.
Step 1. In the current project, create a Student class and type the red box as shown below.

Learning Module on [Course Code]


48

Step 2. To test the Student class above, create a JFrame and name it StudentUI. Design the form as shown
below.

Step 3. In the Click Me button, type the code as below

Student S2 = new Student("Gian", 89.42, 2); // Constructor 2


Student S1 = new Student(1, "Jun", 78.53); // Constructor 1
Student S3 = new Student("Gian", 3); // Constructor 3
S1.Display();
S2.Display();
S3.Display();

Step 4. Run the JFrame program. When you click the button, you should see the output as below

Learning Module on [Course Code]


49

Method Overriding in Java


In any object-oriented programming language, Overriding is a feature that allows a subclass or child class
to provide a specific implementation of a method that is already provided by one of its super-classes or
parent classes. When a method in a subclass has the same name, same parameters or signature and same
return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override
the method in the super-class.

If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been declared by
one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
o Method overriding is used for runtime polymorphism

Learning Module on [Course Code]


50

Rules for Java Method Overriding


1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Example
Step 1. Create a class and name it Parent. Type the code as shown in red box below

Learning Module on [Course Code]


51

Step 2. Create a JFrame form, name it ParentUI. Design the form as shown below.

Step 3. In the button, type the code below.

Parent obj1 = new Parent();


obj1.show();
Parent obj2 = new Child(); //same as Child obj2 = new Child();
obj2.show();

Step 4. When you run the UI, and click the button, you will see pop up message as below.

Learning Module on [Course Code]


52

Note. If we don’t want a method to be overridden, we declare it as final

class Parent
{
// Can't be overridden
final void show() { }
}

class Child extends Parent


{
// This would produce error
void show() { }
}

Summary

In this module, you learned the concept of one of the pillars of OOP, which is polymorphism.
Polymorphism is the state of one having many forms.
You should now have a full understanding on what means by state of one having many forms. It is a
mechanism that allows a single name to represent different code. Because a single name can represent
different code, that name can express many different behaviors. Polymorphism allows you to write that
concept.

Finally, in this module, you learned about two different types of polymorphism, namely method
overriding and method overloading, its concept and its application in creating a real-world application.

Learning Module on [Course Code]


53

References
 Brett D. McLaughlin, Gary Pollice, and Dave West, Head First Object-Oriented Analysis and
Design 1st Ed. (2006)
 Matt Weisfeld Weisfeld, The Object-Oriented Thought Process (Developer's Library) 4th Ed.
(2013)

Web References
 https://www.javatpoint.com/java-oops-concepts
 https://www.udacity.com/course/object-oriented-programming-in-java--ud283
 https://www.edureka.co/blog/object-oriented-programming/
 https://www.ntu.edu.sg/home/ehchua/programming/java/J3a_OOPBasics.html
 https://www.w3resource.com/java-tutorial/java-object-oriented-programming.php
 https://www.udemy.com/course/object-oriented-programming-oops-for-java-certification/
 https://beginnersbook.com/2013/05/method-overloading/
 https://netbeans.org/kb/docs/java/quickstart.html 
 https://www.ntu.edu.sg/home/ehchua/programming/howto/NetBeans_HowTo.html 
 https://netbeans.org/kb/docs/java/gui-functionality.html
 https://www.w3resource.com/c-programming-exercises/input-output/index.php
 https://www.w3schools.com/java/
 https://www.tutorialrepublic.com/twitter-bootstrap-tutorial/
 https://www.w3schools.com/bootstrap4/bootstrap_carousel.asp
 https://www.tutorialspoint.com/bootstrap/bootstrap_tables.htm
 http://binkurt.blogspot.com/2017/10/exercises-to-study-java-stream-api.html
 https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
 https://www.javatpoint.com/java-9-features
 https://www.baeldung.com/java-stream-sum

Learning Module on [Course Code]


54

Learning Module on [Course Code]

You might also like