0% found this document useful (0 votes)
5 views8 pages

Module 2

This learning module from Binalatongan Community College focuses on Object-Oriented Programming (OOP) principles, specifically using Java. It covers key concepts such as encapsulation, data hiding, polymorphism, and inheritance, providing a structured approach to understanding OOP through examples and tasks. The module aims to equip students with a foundational understanding of OOP and its practical applications in programming.

Uploaded by

deveraweng1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views8 pages

Module 2

This learning module from Binalatongan Community College focuses on Object-Oriented Programming (OOP) principles, specifically using Java. It covers key concepts such as encapsulation, data hiding, polymorphism, and inheritance, providing a structured approach to understanding OOP through examples and tasks. The module aims to equip students with a foundational understanding of OOP and its practical applications in programming.

Uploaded by

deveraweng1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Binalatongan Community College

Brgy. Ilang San Carlos City, Pangasinan

Bachelor of Science in Information Technology (BSIT)


LEARNING MODULE

Module No. 2
Subject Code : IT 211
Subject Description : Object Oriented Programming
Term : 1st Semester 2022-2023

I. Learning Objectives:
To have a complete overview of the subject
II. Learning Outcome:
- Understand the fundamentals of Object-Oriented Programming
and the principles behind the programming.
III. Learning Resources/Reference:
- Concise Guide to Object Oriented Programming, Kingsley Sage,
2019
- The Object-Oriented Thought Process Fifth Edition, Matt Weisfeld,
2019
IV. Tasks to Complete:
- Read the Object-Oriented Programming basics with Java
- Learn the importance and the features of an object-oriented design
model inspired by similarity detection by defining the difference.
- Answer the questions in self-assessment.
V. Content:

Object-Oriented Programming Basics With


Java
In his keynote address to the 11th World Computer Congress in 1989,
renowned computer scientist Donald Knuth said that one of the most
important lessons he had learned from his years of experience is that
software is hard to write! Computer scientists have struggled for decades to
design new languages and techniques for writing software. Unfortunately,
experience has shown that writing large systems is virtually impossible.
Small programs seem to be no problem, but scaling to large systems with
large programming teams can result in $100M projects that never work and
are thrown out.
The only solution seems to lie in writing small software units that
communicate via well-defined interfaces and protocols like computer chips.
The units must be small enough that one developer can understand them
entirely and, perhaps most importantly, the units must be protected from
interference by other units so that programmers can code the units in
isolation. The object-oriented paradigm fits these guidelines as designers
represent complete concepts or real world entities as objects with approved
interfaces for use by other objects.
Like the outer membrane of a biological cell, the interface hides the
internal implementation of the object, thus, isolating the code from
interference by other objects. For many tasks, object-oriented programming
has proven to be a very successful paradigm. Interestingly, the first object-
oriented language (called Simula, which had even more features than C++)
was designed in the 1960's, but object-oriented programming has only come
into fashion in the 1990's.
This module is broken down into three sections. First, you will find a
high-level overview that shows object-oriented programming to be a very
natural concept since it mirrors how your hunter-gatherer mind views the
outside world. Second, you will walk through object-oriented programming
by example; learning to use a simple object, examining the definition,
extending the definition, and then designing your own object. Finally, you will
explore the most important concepts in object-oriented programming:
encapsulation, data hiding, messages, and inheritance.

Encapsulation and data hiding


The first and most important design principle we can derive from our
perception of the real world is called encapsulation. When you look at an
animal, you consider it to be a complete entity--all of its behavior and
attributes arise strictly from that animal. It is an independent, completely-
specified, and self-sufficient actor in the world. You do not have to look
behind a big rock looking for another bit of functionality or another creature
that is remotely controlling the animal.
Closely associated with encapsulation is the idea of data hiding. Most
animals have hidden attributes or functionality that are inaccessible or are
only indirectly accessible by other animals. The inner construction and
mechanism of the human body is not usually available to you when
conversing with other humans. You can only interact with human beings
through the approved voice-recognition interface. Bookkeeping routines such
as those controlled by the autonomic nervous system like breathing may not
be invoked by other humans. Without bypassing the approved interface, you
cannot directly measure attributes such as internal body temperature and so
on.
One can conclude that we perceive objects in the world as
encapsulated (selfcontained) entities with approved interfaces that hide
some implementation behavior and attributes. From a design perspective,
this is great because it limits what you have to think about at once and
makes it much easier for multiple programmers to collaborate on a program.
You can think about and design each object independently as well as force
other programmers to interact with your objects only in a prescribed
manner; that is, using only the approved interface. You do not have to worry
about other programmers playing around with the inner workings of your
object and at the same time you can isolate other programmers from your
internal changes.
Encapsulation and data hiding are allowed to varying degrees in non-
objectoriented languages and programmers have used these principles for
decades. For example, in C, you can group related variables and functions in
a single file, making some invisible to functions in other files by labeling
them as static. Conversely, object-oriented languages support these design
principles. In Java, for example, you will use an actual language construct
called a class definition to group variables and functions. You can use access
modifiers like private and public to indicate which class members are visible
to functions in other objects.

The interaction of objects using polymorphism


Encapsulation and data hiding are used to define objects and their
interfaces, but what about the mechanism by which objects interact? In the
real world, animals are self-contained and, therefore, do not physically share
brains. Animals must communicate by sending signals. Animals send signals,
depending on the species, by generating sound waves such as a voice,
images such as a smile, and chemicals such as pheromones.
There is no way for an animal to communicate with another by directly
manipulating the internal organs or brain of another because those
components are hidden within the other animal. Consequently, our brain is
hardwired to communicate by sending signals. If we view the world as a
collection of objects that send and receive messages, what programming
principle can we derive? At first you may suspect that a signal or message is
just a function call. Rather than manipulate the internals of an object, you
might call a function that corresponded to the signal you wanted to send.
Unfortunately, function calls are poor analogs to real world messaging
for two main reasons. First, function calls do things backwards. You pass
objects to functions whereas you send messages to an object. You have to
pass objects to functions for them to operate on because they are not
associated with a particular object. Second, function calls are unique in that
the function's name uniquely identifies what code to run whereas messages
are more generic.
The receiver of a message determines how to implement it. For
example, you can tell a man and a woman both to shave and yet they
respond to the exact same message by doing radically different things. The
truly powerful idea behind message sending lies in its flexibility--you do not
even need to know what sex the human is to tell them to shave. All you need
to know is that the receiver of the message is human. The notion that
similar, but different, objects can respond to the same message is technically
called polymorphism (literally "multiple-forms"). Polymorphism is often called
late binding because the receiver object binds the message to an
appropriate implementation function (method in Java terminology) at run-
time when the message is sent rather than at compile-time as functions are.
Polymorphism's flexibility is derived from not having to change the code that
sends a message when you define new objects. Imagine a manager that
signals employees when to go home at night. A so-called micro-manager
must know all sorts of details about each employee (such as where they live)
to get them home at night.
A manager that delegates responsibility well will simply tell each
employee to go home and let them take care of the details. Surely, adding a
new kind of employee such as a "summer intern" should not force changes in
the manager code. Alas, a micro-manager would in fact have to change to
handle the details of the new employee type, which is exactly what happens
in the function-centric, non-object-oriented programming model. Without
polymorphism, encapsulation's value is severely diminished because you
cannot effectively delegate, that is, you cannot leave all the details within a
selfcontained object. You would need to know details of an object to interact
with it rather than just the approved communication interface.

The relationship between objects and inheritance


Humans rely on their ability to detect similarities between objects to
survive new situations. If an animal has many of the characteristics of a
snake, it is best to leave it alone for fear of a venomous bite. In fact, some
animals take advantage of similarity detectors in other animals by mimicking
more dangerous creatures; some kingsnakes have colored bands like the
deadly coral snake, although in a different order. Similarly, we learn most
easily when shown new topics in terms of how they relate or differ from our
current knowledge base. Our affinity for detecting and using similarity
supports two important ideas in the object-oriented design model:
polymorphism requires a definition of similarity to be meaningful and we can
design new objects as they differ from existing objects.

Behavior versus identity


Sending the same message to two different objects only makes sense
when the objects are similar by some measure. For example, it makes sense
to tell a bird and an airplane to fly because they share behavior. On the other
hand, telling a dog to sit makes sense, but telling a cat to sit makes no
sense; well, it is a waste of time anyway. Telling a human to shave makes
sense, but telling an airplane to shave does not.
One way to define similarity is to simply say that the objects implement or
respond to the same message or set of messages; that is to say, they share
at least a partial interface (common subset of public methods). This is the
approach of early object-oriented languages such as SmallTalk. Another
similarity measure corresponds to the relationship between the objects
themselves rather than just their interfaces. If two objects are the same kind
of object then it makes sense that they also share a partial interface. For
example, males and females are kinds of humans and, hence, share a
common interface (things that all humans can do like shave, sleep, sit and so
on). Java uses object relationships to support polymorphism.

The inheritance relationship


What metaphor does Java use to specify object relationships? Java uses
inheritance. That is, if man and woman objects are kinds of humans then
they are said to inherit from human and therefore share the human
interface. Consequently, we are able to treat them generically as humans
and do not have to worry about their actual type.
If we had a list of humans, we could walk down the list telling everyone to
shave without concern for the objects' concrete type (either man or woman).
Late-binding ensures that the appropriate method is invoked in response to
the shave message depending on the concrete type at runtime. All objects
have exactly one parent, inheriting all of the data and method members
from the parent. The inheritance relationships among objects thus form a
tree, with a single predefined root called Object representing the generic
object.

Defining by difference
The second important feature of an object-oriented design model inspired
by similarity detection is "defining by difference." If I want to define a new
object in my system, an efficient way to do so is to describe how it differs
from an existing object. Since man and woman objects are very similar, the
human object presumably contains most of the behavior. The man object, for
example, only has to describe what distinguishes a man from the abstract
notion of a human, such as buying lots of electronic toys.

Object-Oriented Programming By Example


In this module is a starting point for learning object-oriented programming. It
parallels the process you would follow to become a car designer: first you
learn to drive a car, then you look under the hood, next you learn to modify
and repair engines, finally you design new cars. Specifically, in this section,
you will:
1. learn how to use a trivial object
2. study the object definition
3. learn to modify an object definition
4. learn how to define new objects

Inheritance
A Rectangle object contains two Point objects. A Rectangle is not a kind of
Point nor is a Point a kind of Rectangle; their relationship is one of
containment. There is another kind of object relationship called inheritance
in which one object is a specialization of another. You say that a class
extends or derives from another class and may add data or behavior.
The original class is called the superclass and the class derived from it is
called the subclass. The first important concept behind inheritance is that the
subclass can behave just like any instance of the superclass. For example, if
you do not add any data members nor extend the behavior of Rectangle, you
have simply defined another name for a Rectangle:
class AnotherNameForRectangle extends Rectangle {

You can refer to AnotherNameForRectangle as a Rectangle:

AnotherNameForRectangle ar = ...; Rectangle r = ar; // OK: ar is a kind of Rectangle

If instance ar is a kind of rectangle, you can ask for its dimensions:

Dimension d = [Link]();
The definition of class AnotherNameForRectangle is empty, so how can
you ask for its dimensions? The subclass inherits all data and behavior of
Rectangle, therefore, object ar can masquerade as a plain Rectangle. Just as
you are born with nothing, but inherit money and characteristics from your
parents, AnotherNameForRectangle inherits data and behavior from its
parent: Rectangle. One way to look at inheritance of data and behavior is to
consider it a language construct for a "live" cut-n-paste. As you change the
definition of a class, all subclasses automatically change as well.
The second important concept behind inheritance is that you may define
new objects as they differ from existing objects, which promotes code reuse.
For example, your design may call for a FilledRectangle object. Clearly, a
filled rectangle is a kind of rectangle, which allows you to define the new
class as it differs from Rectangle. You may extend Rectangle by adding data:
class FilledRectangle extends Rectangle {
protected String fillColor = "black"; // default color }
Unfortunately, FilledRectangle does not, by default, know how to initialize
itself as a kind of Rectangle. You must specify a constructor, but how does a
subclass initialize the contributions from its superclass? A subclass
constructor can invoke a superclass constructor:
class FilledRectangle extends Rectangle {
protected String fillColor = "black"; // default color public FilledRectangle(Point ul, Point lr,
String c)
{ super(ul,lr); // calls constructor: Rectangle(ul,lr)
fillColor = c; // initialize instance vars of this
}
}
When you construct a FilledRectangle, space is allocated for an object the
size of a Rectangle plus a String contributed by subclass FilledRectangle.
Then Java initializes the Rectangle portion of the object followed by the
FilledRectangle portion. The new operation for FilledRectangle takes three
arguments, two of which are used to initialize the Rectangle component:
Point p = new Point(10,10);
Point q = new Point(20,40);
FilledRectangle fr = new FilledRectangle(p,q,"red");
You may add behavior to subclasses as well. For example, to allow other
objects to set and get the fill color, add a so-called "getter/setter" pair:
class FilledRectangle extends Rectangle {

protected String fillColor = "black"; // default color


public FilledRectangle(Point ul, Point lr, String c) {
super(ul,lr); // calls constructor: Rectangle(ul,lr)
fillColor = c; // initialize instance vars of this
}
public void setFillColor(String c) { fillColor = c;
}
public String getFillColor() {
return fillColor;
}
}
Another object may then access the added functionality:
[Link]("blue");
String c = [Link]();
Recall that, since FilledRectangle is a Rectangle, you may refer to it as such:
Rectangle r = fr;

But, even though r and fr physically point at the same object in memory, you
cannot treat the Rectangle as a FilledRectangle:
[Link]("blue");// no problem

Rectangle r = fr; // r and fr point to same object

[Link]("blue"); // ILLEGAL!!!

Reference r has a restricted perspective of the filled rectangle.

VI. Assessment: Quiz


Quiz will be sent through Google Forms

You might also like