0% found this document useful (0 votes)
5 views

OOP Note(s-note)_082434-1

Uploaded by

austinambrose111
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 views

OOP Note(s-note)_082434-1

Uploaded by

austinambrose111
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
You are on page 1/ 13

GET 211

COMPUTER PROGRAMMING

OBJECT ORIENTED PROGRAMMING

Object-oriented programming (OOP) is a programming style that uses objects to model the real
world scenarios. In OOP, you create classes and objects, and use those objects to build
programs. OOP is a popular way of programming because it allows you to easily create complex
systems by breaking them down into smaller, more manageable pieces. There are many different
object-oriented languages, but the most popular ones are Java, C++, and Python.

Overview
TYPES OF PROGRAMMING LANGUAGES
Different programming languages are in use today, but they fall into five main categories
according to their purpose. They include:
Procedural Programming Language: In procedural programming language, the programmer
specifies what has to be done and how it can be done (i.e. the step by step procedure of it). Thus,
a program written using procedural language works with the state of machine. It allows a
programmer to write instructions (called procedures) a computer can execute. These instructions
tell a computer what operations to perform on given data and how these operations should be
performed. In otherwords, It’s a language that requires the programmer to tell not only ’What
To Do’ but also ’How To Do It’. Procedural Language is also known as 3GL (third generation
language). It is a type of programming language that follows a procedure; set of commands or
guidelines that must (or required) be followed for smooth execution of the programs. It works on step
by step basis. Its basic idea is to have a program specify the sequence of steps that implements a
particular algorithm. Hence, Procedural languages are based on algorithms.
Examples: FORTRAN, BASIC, C, PASCAL, ALGOL, JAVA, COBOL

Functional Programming Language: A functional programming language emphasizes


functions that return values, which can be used by other functions or be assigned as values to
variables or data structures. It treats complex computation as the evaluation of mathematical
functions and avoids state and mutable data. It handles pure functions, recursions, evaluations,
etc. Functional languages were designed with theorem-proving in mind rather than traditional
computer applications. Some programming languages that supports function programming
include: Haskell, JavaScript, Python, Scala, Erlang, Lisp, ML, Clojure, OCaml, Common Lisp,
Racket.
Eg of a Pure Function
sum(x, y) //sum is function taking x and y as arguments
return x + y //sum is returning sum of x and y without changing them

Eg of Recursion

fib(n)
if (n <= 1)
return 1;
else
return fib(n - 1) + fib(n - 2);

Functional Programming Language is a declarative style language. Its main focus is on “what to
solve,” in contrast to an imperative style, where the main focus is on “how to solve.” It uses
expressions instead of statements. An expression is evaluated to produce a value, whereas a statement
is executed to assign variables.

Scripting Programming Language: A scripting programming language supports scripts—


programs written for a special run-time environment that automate tasks normally performed by
humans—as opposed to standalone programs. In computing, a script is a relatively short and simple set of
instructions that typically automate a manual process. The act of writing a script is called scripting.
2 - types of scripting language
Server-side scripting language: Is often used to create dynamic websites and platforms, handle
user queries, generate and provide data, and others. Used to run off a web server; and since it
performs from the back-end side, the script is not visible to the users. Because of that, it is a
more secure approach. Examples: PHP, Python, Node.js, Perl, and Ruby.
Client-side scripting language
Unlike the above, client-side scripting languages run off the user’s browser. It is usually
performed at the front end, which makes it visible to users and makes it less vulnerable to
exploits and leaks. As such, it is often used to build user interfaces and lighter functionality .
Since it runs locally, they usually provide better performance and, therefore, do not strain your
server. Examples: HTML, CSS, jQuery, and JavaScript.

Logic Programming Language: A logic programming language allows programmers to write


programs based on rules expressed in logical form. This type of programming language is naturally
designed to answer queries. Its used in any domain where a large amount of data must be analyzed to make
decisions. However, it is most commonly applied to a few subjects. Note that, a pure logic programming
environment does not use control statements or connective code. The program must generate all
responses based on its library of facts and axioms.
Some logic languages, include: ASP and Datalog.
Eg :
x is true, or
x is y, where y is a statement about x.

Logic programming
Logic programming is a paradigm that uses a system of facts and rules. It is commonly used in
the artificial intelligence and machine learning domains
It was originally designed to help study knowledge representation and artificial intelligence.
Logic programming is a variation of declarative programming based on a type of formal logic
called Predicate Calculus. Declarative languages describe what the program should do, but not
how to do it. The precise algorithms and processing methods are left up to the language, which
is expected to generate the proper outcome. Logic programming should not be confused with
programming logic, which is a more general study of how logical rules apply in computer
programming.

Logic programs are completely data-driven and do not typically include any connective logic.
Instead, the programs use a set o
Object-Oriented Programming Language: It has become increasingly popular since the
mid-1980s and is now almost universally supported in modern programming languages.
Object-Oriented Programming Language (OOP)
Explained:
In object-oriented programming (OOP), objects are the basic elements of the program. In fact,
everything in OOP is an object: the variables, the functions, even the classes themselves.
Working with objects can be quite complex, but with a little practice, you’ll find that object-
oriented programming is one of the most powerful tools in your programming.
It’s simply a type of programming approach that uses the concepts of objects and classes. A
program written within the Object-Oriented Programming approach will have reusable blocks
of codes termed classes. These classes are further used for creating instances of the objects.
Due to several benefits offered by Object-Oriented Programming, many programming
languages have been developed following the general concepts of OOP. The programming
languages that follow OOP are Java, Python, and C++. Also a class may be defined as a
blueprint for creating specific objects. Whenever a class is specified, it means that attributes
are shared within the class.

In summary, OOP revolves around the concept of objects. In the area of software
development, Object-Oriented Programming language has become a fundamental part.
Mainly with developing languages like Java and C++, software development would have
been a problematic approach. Therefore, without having a clear concept and
understanding of Object-Oriented Programming, software development for mobile
couldn’t be carried out. Apart from mobile application development, even in web
development, OOP has played a crucial role, mainly in developing OOP languages such
as Python, Ruby, and PHP.

In as much as OOP uses objects in programming, the reason to use OOPs in a code is to
increase the reusability and readability of a code. The main aim of OOP is to bind together the
data and the functions that operate on them so that no other part of the code can access this data
except that function. There are some principles that work in OOP.

Simple Concepts in OOP? (Classes, Properties, Methods, Objects)


In order to understand the object-oriented programming , let’s take a closer look at some of the
simple concepts as well as the main principles/characteristics of object-oriented programming.

1. Class:
A class is a blueprint for creating objects. It is a template for an object, and it defines the
object’s properties and methods.
A class is also a user-defined data type. It consists of data members and member functions,
which can be accessed and used by creating an instance of that class. It represents the set of
properties or methods that are common to all objects of one type. A class is like a blueprint for
an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage
are their properties.
2. Properties: A property is a characteristic of an object. It is a value that describes the object.
2.

For example, a car object might have properties like color and make.

3. Methods: A method is an action that can be performed on an object. It is a function that is


associated with an object. For example, a car object might have methods like start and stop.
4. Object:
It is a basic unit of OOP and represents the real-life entities. An Object is an instance of a
Class. When a class is defined, no memory is allocated but when it is instantiated (i.e. an
object is created) memory is allocated. An object has an identity, state, and behavior. Each
object contains data and code to manipulate the data. Objects can interact without having to
know details of each other’s data or code, it is sufficient to know the type of message accepted
and type of response returned by the objects.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed,
Bark, Sleep, and Eats.

Object
Difference between Java Class and Objects
The differences between class and object in Java are as follows:

Class Object

Class is the blueprint of an object. It is


An object is an instance of the class.
used to create objects.

No memory is allocated when a class is


Memory is allocated as soon as an object is created.
declared.

A class is a group of similar objects. An object is a real-world entity such as a book, car, etc.

Class is a logical entity. An object is a physical entity.

A class can only be declared once. Objects can be created many times as per requirement.

An example of class can be a car. Objects of the class car can be BMW, Mercedes, Ferrari, etc.
The Four Main Principles (pillars/characteristics) of Object-Oriented Programming
(OOP) are:
 Abstraction: Using simplified classes, rather than complex implementation code, to access
objects.
 Encapsulation: Enclosing data by containing it within an object.
 Inheritance: A new class automatically inherits the same properties and functionalities as its
parent class.
 Polymorphism: Objects can take on many forms or types.
These provide a better programming style, as the class can be instantiated once a call has been
created which could be used in any part of the application.

In object-oriented programming (OOP), we often discuss the


four pillars of its foundation. They’re like the building blocks
that help us structure our code in a more organized and
efficient way.

1. Data Abstraction (Data Hide):


Data abstraction is one of the most essential and important features of object-oriented
programming. Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation.
Abstraction in Java is the process in which we only show essential details/functionality to the
user. The non-essential implementation details are not displayed to the user.
Simple Example to understand Abstraction:
Television remote control is an excellent example of abstraction. It simplifies
the interaction with a TV by hiding the complexity behind simple buttons and
symbols, making it easy without needing to understand the technical details of
how the TV functions.
In Java, abstraction is achieved by interfaces and abstract classes. Meaning, we can achieve
100% abstraction using interfaces.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object ignoring the irrelevant details. The properties and behaviours of an
object differentiate it from other objects of similar type and also help in classifying/grouping
the objects.
Abstraction: Abstraction is about focusing on the essential qualities of an object while ignoring the
irrelevant details. It’s like driving a car without needing to understand the intricate workings of the engine.
In OOP, we create classes that represent real-world objects or concepts, abstracting away the complexities
to make them easier to work with and understand.
2. Encapsulation (Data Hide):
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates. In Encapsulation, the variables or data of
a class are hidden from any other class and can be accessed only through any member function
of their class in which they are declared. As in encapsulation, the data in a class is hidden
from other classes, so it is also known as data-hiding.

Encapsulation: Think of encapsulation as wrapping up data (variables) and methods (functions) into a
single unit, known as a class. It’s like putting your code into a neat little package, where the inner
workings are hidden from the outside world and only the necessary interfaces are exposed. This helps
better manage complexity and prevent unauthorized access to or modification of data.
Encapsulation
Imagine encapsulation as putting your code into a black box. You have this box (a class), and you throw
all your variables and methods inside. Then, you seal it shut, only allowing access through a few
predefined openings (methods). This way, you have better control over what goes in and out, ensuring that
your data stays safe and your code remains manageable.

Example: Consider a real-life example of encapsulation, in a company, there are different


sections like the accounts section, finance section, sales section, etc. The finance section
handles all the financial transactions and keeps records of all the data related to finance.
Similarly, the sales section handles all the sales-related activities and keeps records of all the
sales. Now there may arise a situation when for some reason an official from the finance
section needs all the data about sales in a particular month. In this case, he is not allowed to
directly access the data of the sales section. He will first have to contact some other officer in
the sales section and then request him to give the particular data. This is what encapsulation is.
Here the data of the sales section and the employees that can manipulate them are wrapped
under a single name “sales section”.
 Technically in encapsulation, the variables or data of a class is hidden from any other class
and can be accessed only through any member function of its own class in which it is
declared.
 As in encapsulation, the data in a class is hidden from other classes using the data hiding
concept which is achieved by making the members or methods of a class private, and the
class is exposed to the end-user or the world without providing any details behind
implementation using the abstraction concept, so it is also known as a combination of
data-hiding and abstraction.
 Encapsulation can be achieved by Declaring all the variables in the class as private and
writing public methods in the class to set and get the values of variables.
 It is more defined with the setter and getter method.

Advantages of Encapsulation
 Data Hiding: it is a way of restricting the access of our data members by hiding the
implementation details. Encapsulation also provides a way for data hiding. The user will
have no idea about the inner implementation of the class. It will not be visible to the user
how the class is storing values in the variables. The user will only know that we are
passing the values to a setter method and variables are getting initialized with that value.
 Increased Flexibility: We can make the variables of the class read-only or write-only
depending on our requirements. If we wish to make the variables read-only then we have
to omit the setter methods like setName(), setAge(), etc. from the above program or if we
wish to make the variables write-only then we have to omit the get methods like
getName(), getAge(), etc. from the above program
 Reusability: Encapsulation also improves the re-usability and is easy to change with new
requirements.
 Testing code is easy: Encapsulated code is easy to test for unit testing.
 Freedom to programmer in implementing the details of the system: This is one of the
major advantage of encapsulation that it gives the programmer freedom in implementing
the details of a system. The only constraint on the programmer is to maintai n the abstract
interface that outsiders see.

Disadvantages of Encapsulation in Java


 Can lead to increased complexity, especially if not used properly.
 Can make it more difficult to understand how the system works.
 May limit the flexibility of the implementation.

3. Inheritance (Re-usability):
Inheritance allows the user to reuse the code whenever possible and reduce its redundancy. In
Java, Inheritance is an important pillar of OOP(Object-Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features(fields and methods) of
another class. In Java, Inheritance means creating new classes based on existing ones . A class
that inherits from another class can reuse the methods and fields of that class. In addition, you
can add new fields and methods to your current class as well.
Inheritance: Inheritance is a powerful concept where a new class can inherit properties and behavior
(methods) from an existing class. It’s like passing down traits from parents to children. This helps promote
code reusability and establish hierarchical relationships between classes, where more specialized classes
can extend or modify the behavior of more generalized ones.
Why Do We Need Java Inheritance?
 Code Reusability: The code written in the Superclass (parent) is common to all subclasses
(child). Child classes can directly use the parent class code.
 Method Overriding: Method Overriding is achievable only through Inheritance. It is one of
the ways by which Java achieves Run Time Polymorphism.
 Abstraction: The concept of abstract where we do not have to provide all details is
achieved through inheritance. Abstraction only shows the functionality to the user.
Important Terminologies Used in Java Inheritance
 Class: Class is a set of objects which shares common characteristics/ behavior and
common properties/attributes. Class is not a real-world entity. It is just a template or
blueprint or prototype from which objects are created.
 Super Class/Parent Class: The class whose features are inherited is known as a
superclass(or a base class or a parent class).
 Sub Class/Child Class: The class that inherits the other class is known as a subclass(or a
derived class, extended class, or child class). The subclass can add its own fields and
methods in addition to the superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to create
a new class and there is already a class that includes some of the code that we want, we can
derive our new class from the existing class. By doing this, we are reusing the fields and
methods of the existing class.

How to Use Inheritance in Java?


The extends keyword is used for inheritance in Java. Using the extends keyword indicates
you are derived from an existing class. In other words, “extends” refers to increased
functionality.
Syntax :
class derived-class extends base-class
{
//methods and fields
}

4. Polymorphism (Object to take many Forms):


The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For example,
A person at the same time can have different characteristics. Like a man at the same time is a
father, a husband, an employee. So the same person posses different behavior in different
situations. This is called polymorphism.
What is Polymorphism in Java?
Polymorphism is considered one of the important features of Object-Oriented Programming. It
allows us to perform a single action in different ways. In other words, polymorphism allows
you to define one interface and have multiple implementations. The word “poly” means many
and “morphs” means forms, So it means many forms.
Polymorphism in Java is a concept that allows objects of different classes to be treated as
objects of a common class. It enables objects to behave differently based on their specific class
type.
Polymorphism: Polymorphism allows objects of different classes to be treated as objects of a common
superclass. It’s like the ability of a function to work with different types of data. This enables flexibility in
designing and interacting with objects, as methods can behave differently based on the specific
implementation in each subclass. Polymorphism is often achieved through method overriding (having a
subclass provide a specific implementation of a method) and method overloading (providing multiple
methods with the same name but different parameters).
Advantages of Polymorphism in Java
1. Increases code reusability by allowing objects of different classes to be treated as objects
of a common class.
2. Improves readability and maintainability of code by reducing the amount of code that
needs to be written and maintained.
3. Supports dynamic binding, enabling the correct method to be called at runtime, based on
the actual class of the object.
4. Enables objects to be treated as a single type, making it easier to write generic code that
can handle objects of different types.

Disadvantages of Polymorphism in Java


1. Can make it more difficult to understand the behavior of an object, especially if the code is
complex.
2. This may lead to performance issues, as polymorphic behavior may require additional
computations at runtime.

Interface
An Interface can be described as an abstract type used to specify the behavior of a class. Its
simply a blueprint of a behavior. A Java interface contains static constants and abstract
methods.
What are Interfaces in Java?
The interface in Java is a mechanism to achieve abstraction. There can only be abstract
methods in Java interface, not the method body. It is used to achieve abstraction and multiple
inheritances in Java using Interface. In other words, you can say that interfaces can have
abstract methods and variables. It cannot have a method body. Java Interface also represents
the IS-A relationship.
Uses of Interfaces in Java
Uses of Interfaces in Java are mentioned below:
 It is used to achieve total abstraction.
 Since java does not support multiple inheritances in the case of class, by
using an interface it can achieve multiple inheritances.
 Any class can extend only 1 class, but can any class implement an infinite
number of interfaces.
 It is also used to achieve loose coupling.
 Interfaces are used to implement abstraction.
Implementation: To implement an interface, we use the keyword implements

So, the question arises why use interfaces when we have abstract classes?
The reason is, abstract classes may contain non-final variables, whereas variables in the
interface are final, public, and static.
Difference Between Class and Interface
Although Class and Interface seem the same there have certain differences between Classes and
Interface. The major differences between a class and an interface are mentioned below:

Class Interface

In class, you can instantiate variables In an interface, you can’t instantiate variables and create an
and create an object. object.

A class can contain concrete (with The interface cannot contain concrete (with
implementation) methods implementation) methods.

The access specifiers used with Classes


In Interface only one specifier is used- Public.
are private, protected, and public.

Aggregation in Object Oriented Programming


Is a fundamental concepts in oop used to create more complex and modular systems by
organizing objects into meaningful relationships.
It is a special form of Association where:
 It represents Has-A’s relationship.
 It is a unidirectional association i.e. a one-way relationship. For example, a department
can have students but vice versa is not possible and thus unidirectional in nature.
 In Aggregation, both entries can survive individually which means ending one entity
will not affect the other entity.

AFIT Student

Staff

Advantage / Benefits of OOPS


1. Troubleshooting is easier with the OOP language
Suppose there is an error within the code, and the user has no idea where the bug lies. Also,
the user has no idea where to look into the code to fix the error. This is quite difficult for
standard programming languages. However, when Object-Oriented Programming is applied,
the user knows exactly where to look into the code whenever there is an error. There is no
need to check other code sections as the error will show where the trouble lies. Let’s
understand it by this example, you are using your mobile phone and suddenly the screen turns
white, and then turned off. You infer that the reason behind this must be a problem with the
motherboard of your phone. Encapsulation is the reason behind this, there is no need to go
afterevery code in order to understand a problem. It is mainly encapsulation that makes the
objects self-contained. This further helps in troubleshooting and easier collaborative
development.
2. Code Reusability (Inheritance): One of two important concepts that are provided by
Object-Oriented Programming is the concept of inheritance. Through inheritance, the same
attributes of a class are not required to be written repeatedly. This avoids the issues where the
same code has to be written multiple times in a code. With the introduction of the concept of
classes, the code section can be used as many times as required in the program. Through the
inheritance approach, a child class is created that inherits the fields and methods of the parent
class. The methods and values that are present in the parent class can be easily overridden.
Through inheritance, the features of one class can be inherited by another class by extending
the class. Therefore, inheritance is vital for providing code reusability and also multilevel
inheritance.
3. Productivity: The productivity of two codes increases through the use of Object-Oriented
Programming. This is because the OOP has provided so many libraries that new programs
have become more accessible. Also, as it provides the facility of code reusability, the length
of a code is decreased, further enhancing the faster development of newer codes and
programs. One of the advantages of using OOP in Java is the productivity of a code as it
doesn’t only saves time but also the possibility of errors. When a code is being put into a
library, the steps for manual programming are not required. The codes can be easily accessed
in these libraries.

4. Data Redundancy: By the term data redundancy, it means data is repeated twice. This
means that the same data is present more than one time. In Object-Oriented Deprogramming ,
the data redundancy is considered to be an advantage. For example, the user wants to have a
functionality that is similar to almost all the classes. In such cases, the user can create
classes with similar functionaries and inherit them wherever required.
Although redundancy by the term is not appealing here it is considered as one of the
advantages of object oriented programming, the main reason is that it reduces the repetition
of a mundane task. If some data is required to be used again then the data from a similar
functionary can be utilised. And the efforts can go into doing those tasks which require more
attention.
5. Code Flexibility (Polymorphism): The flexibility is offered through the concept of
Polymorphism. A scenario can be considered for a better understanding of the concept. A
person can behave differently whenever the surroundings change. For example, if the person
is in a market, the person will behave like a customer, or the behavior might get changed to a
student when the person is in a school or any institution.
In this example, it can be observed that different behaviors are shown by the same person
whenever the surroundings around the person get changed. This could explain the concept of
Polymorphism and its flexibility. The developers benefit through Polymorphism in the
following ways: simplicity and extensibility. Polymorphism is one of the benefits of oop as it
gives scope to a code to be in more than one form.
6. Solving problems
Problems can be efficiently solved by breaking down the problem into smaller pieces and this
makes one of the big advantages of object-oriented programming. If a complex problem is
broken down into smaller pieces or components, it becomes a good programming practice.
Considering this fact, OOPS utilizes this feature, and once the problem is broken down, these
broken pieces can be used again to solve other problems.
7. Security
Because of the concept of data abstraction in OOPS, only a limited amount of data is shown
to the user which makes good benefits of OOP. The rest data is not exposed while exposing
only the required amount of data. Therefore, it allows the maintenance of security. Another
set of benefits of oop in java concept of abstraction is used to hide the complexity from other
users and demonstrate the element’s information as per the requirements. It also helps in
avoiding repetitive code. Another concept provided in OOPS is the feature of encapsulation
that allows the protection of the data in the classes from getting accessed by the system. All
the internal contents in the class can be safeguarded. In Java, encapsulation is mainly used for
restricting access to the class fields directly while setting all the fields of the class to private.
8. Code Organization
Benefits of OOP in Java is that Object-Oriented Programming (OOP) offers a significant
advantage by allowing developers to encapsulate data and behavior within classes and
objects. Advantages of OOP includes that this approach emphasizes maintaining data
integrity and preventing unintended data access. By assigning distinct roles and functions to
classes, developers can effectively segment the codebase into smaller, autonomous modules.
This practice enhances code extensibility, simplifies maintenance tasks, ultimately
minimizing the efforts and resources required for debugging, and issue resolution within code
blocks.
9. Make Code More Modular
One advantage of object-oriented programming is that it makes code more modular. This
means, you can reuse objects in different programs, or even in different parts of the same
program. For example, if you have an object that represents a planet, you could use that object in
a program that simulates the solar system, or in a program that is just a database of planets.
10. Make Code Easier To Understand
Another advantage of object-oriented programming is that it can make code easier to
understand. This is because the objects represent real-world entities, so it can be easier to
visualize what the code is doing. For example, if you have a program that simulates the solar
system, it would be easier to understand if the code was organized into objects like planets, stars,
and galaxies.
Disadvantage
#1: Complex To Initially Understand
One disadvantage is that object-oriented programming can be more complex than
other styles of programming. This is because you have to design the objects and their
interactions, which can be a lot of work.
#2: Can Be Slower To Execute
This is because the objects have to interact with each other, which takes processing
time.
Despite these disadvantages, object-oriented programming is a powerful tool that can be used to
write efficient and understandable code.

You might also like