Professional Documents
Culture Documents
STUDENT
Name:
Learning Module on [Course Code]
Student Number:
Program:
INSTRUCTIONS TO THE STUDENTS
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.
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.
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.
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
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.
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.
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.
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.
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
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
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.
//you can create multiple objects (student1, student2…) for the classStudent Information
StudentInformation student1 = new StudentInformation();
StudentInformation student2 = new StudentInformation();
Student1.name="Test";
Student2.name="Test2";
//call the method
Student1.display();
Student2.display();
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
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.
b.
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.
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
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).
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.
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.
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.
Solution:
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:
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.
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:
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
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
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 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
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
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;
} }
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
Keyword THIS is a reference variable in Java that refers to the current object.
Example
Step 1. In the current project, create Account class. Type the code in red box as shown below
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.
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
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.
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.
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
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.
class Animal {
public String eat() {
return "eat";
}
public String sleep() {
return "sleep";
}
}
class Dog extends Animal{
public String Bark() {
return "Dog bark";
}}
Step 3. Create a JFrame and name it AnimalUI. Design the form as shown below.
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.
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.
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.
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.
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.
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.
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
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
Step 4. Run the JFrame form and click the button. You should see two message boxes as below
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.
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
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:
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:
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.
Step 5. Run the JFrame and click the button. You should see two messageboxes as shown below
Step 2. Create a JFrame form to test the Demo class shown below.
Step 4. Run the JFrame and click the button. You should see a message box as below
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");
}
}
As you see that this time type promotion didn’t happen because there was a method with matching
argument type.
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.
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.
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.
Step 1. In the current project, create a class Animal and type the code in red box below.
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.
Step 4. Run the JFrame program and click the proceed button. You should see the output as shown below.
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.
Step 2. To test the Student class above, create a JFrame and name it StudentUI. Design the form as shown
below.
Step 4. Run the JFrame program. When you click the button, you should see the output as below
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.
Example
Step 1. Create a class and name it Parent. Type the code as shown in red box below
Step 2. Create a JFrame form, name it ParentUI. Design the form as shown below.
Step 4. When you run the UI, and click the button, you will see pop up message as below.
class Parent
{
// Can't be overridden
final 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.
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