0% found this document useful (0 votes)
2 views10 pages

Oops

The document provides an overview of Object-Oriented Programming (OOP) principles, including structured and procedural programming, and highlights key concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It also discusses the advantages and disadvantages of OOP, as well as the Java programming language, its package system, and exception handling. Overall, the document emphasizes the evolution of programming methodologies and the significance of OOP in modern software development.

Uploaded by

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

Oops

The document provides an overview of Object-Oriented Programming (OOP) principles, including structured and procedural programming, and highlights key concepts such as classes, objects, encapsulation, inheritance, and polymorphism. It also discusses the advantages and disadvantages of OOP, as well as the Java programming language, its package system, and exception handling. Overall, the document emphasizes the evolution of programming methodologies and the significance of OOP in modern software development.

Uploaded by

Shubhangi Tyagi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

OOPs | Object Oriented Design

Object oriented design started right from the moment computers were invented. Programming was
there, and programming approaches came into the picture. Programming is basically giving certain
instructions to the computer.
At the beginning of the computing era, programming was usually limited to machine language
programming. Machine language means those sets of instructions that are specific to a particular
machine or processor, which are in the form of 0‟s and 1‟s. These are sequences of bits (0100110…).
But it‟s quite difficult to write a program or develop software in machine language.
It‟s actually impossible to develop software used in today‟s scenarios with sequences of bits. This was
the main reason programmers moved on to the next generation of programming languages,
developing assembly languages, which were near enough to the English language to easily
understand. These assembly languages were used in microprocessors. With the invention of the
microprocessor, assembly languages flourished and ruled over the industry, but it was not enough.
Again, programmers came up with something new, i.e., structured and procedural programming.

Structured Programming –
The basic principle of the structured programming approach is to divide a program into functions and
modules. The use of modules and functions makes the program more understandable and readable. It
helps to write cleaner code and to maintain control over the functions and modules. This approach
gives importance to functions rather than data. It focuses on the development of large software
applications, for example, C was used for modern operating system development. The programming
languages: PASCAL (introduced by Niklaus Wirth) and C (introduced by Dennis Ritchie) follow this
approach.

Procedural Programming Approach –


This approach is also known as the top-down approach. In this approach, a program is divided into
functions that perform specific tasks. This approach is mainly used for medium-sized applications.
Data is global, and all the functions can access global data. The basic drawback of the procedural
programming approach is that data is not secured because data is global and can be accessed by any
function. Program control flow is achieved through function calls and goto statements. The
programming languages: FORTRAN (developed by IBM) and COBOL (developed by Dr Grace Murray
Hopper) follow this approach.
These programming constructs were developed in the late 1970s and 1980s. There were still some
issues with these languages, though they fulfilled the criteria of well-structured programs, software etc.
They were not as structured as the requirements were at that time. They seem to be over-generalised
and don‟t correlate with real-time applications.
To solve such kinds of problems, OOP, an object-oriented approach was developed as a solution.

The Object-Oriented Programming (OOP) Approach –


The OOP concept was basically designed to overcome the drawback of the above programming
methodologies, which were not so close to real-world applications. The demand was increased, but
still, conventional methods were used. This new approach brought a revolution in the programming
methodology field.
Object-oriented programming (OOP) is nothing but that which allows the writing of programs with the
help of certain classes and real-time objects. We can say that this approach is very close to the real-
world and its applications because the state and behaviour of these classes and objects are almost
the same as real-world objects.
Let‟s go deeper into the general concepts of OOP, which are given below:

What Are Class & Object?


It is the basic concept of OOP; an extended concept of the structure used in C. It is an abstract and
user-defined data type. It consists of several variables and functions. The primary purpose of the class
is to store data and information. The members of a class define the behaviour of the class. A class is
the blueprint of the object, but also, we can say the implementation of the class is the object. The class
is not visible to the world, but the object is.
Data Abstraction –
Abstraction refers to the act of representing important and special features without including the
background details or explanation about that feature. Data abstraction simplifies database design.

1. Physical Level:
It describes how the records are stored, which are often hidden from the user. It can be described with
the phrase, “block of storage.”
2. Logical Level:
It describes data stored in the database and the relationships between the data. The programmers
generally work at this level as they are aware of the functions needed to maintain the relationships
between the data.
3. View Level:
Application programs hide details of data types and information for security purposes. This level is
generally implemented with the help of GUI, and details that are meant for the user are shown.

Encapsulation –
Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). It describes
the idea of wrapping data and the methods that work on data within one unit, e.g., a class in Java. This
concept is often used to hide the internal state representation of an object from the outside.

Inheritance –
Inheritance is the ability of one class to inherit capabilities or properties of another class, called the
parent class. When we write a class, we inherit properties from other classes. So when we create a
class, we do not need to write all the properties and functions again and again, as these can be
inherited from another class which possesses it. Inheritance allows the user to reuse the code
whenever possible and reduce its redundancy.

Polymorphism –
Polymorphism is the ability of data to be processed in more than one form. It allows the performance
of the same task in various ways. It consists of method overloading and method overriding, i.e., writing
the method once and performing a number of tasks using the same method name.
Access Modifiers in C++
Access modifiers are used to implement an important feature of Object-Oriented Programming known
as Data Hiding. Consider a real-life example:
The Indian secret informatic system having 10 senior members have some top secret regarding
national security. So we can think that 10 people as class data members or member functions who
can directly access secret information from each other but anyone can‟t access this information other
than these 10 members i.e. outside people can‟t access information directly without having any
privileges. This is what data hiding is.
Access Modifiers or Access Specifiers in a class are used to set the accessibility of the class
members. That is, it sets some restrictions on the class members not to get directly accessed by the
outside functions.
There are 3 types of access modifiers available in C++:
1. Public
2. Private
3. Protected

Friend class and function in C++


Friend Class A friend class can access private and protected members of other class in which it is declared as
friend. It is sometimes useful to allow a particular class to access private members of other class. For example
a LinkedList class may be allowed to access private members of Node.
Friend Function Like friend class, a friend function can be given special grant to access private and protected
members. A friend function can be:
a) A method of another class
b) A global function
Following are some important points about friend functions and classes:
1) Friends should be used only for limited purpose. too many functions or external classes are
declared as friends of a class with protected or private data, it lessens the value of encapsulation of
separate classes in object-oriented programming.
2) Friendship is not mutual. If class A is a friend of B, then B doesn‟t become a friend of A
automatically.
3) Friendship is not inherited (See this for more details)
4) The concept of friends is not there in Java.

Local Classes in C++


A class declared inside a function becomes local to that function and is called Local Class in C++. For example,
in the following program, Test is a local class in fun().
Following are some interesting facts about local classes.
1) A local class type name can only be used in the enclosing function.
2) All the methods of Local classes must be defined inside the class only.
3) A Local class cannot contain static data members. It may contain static functions though.
4) Member methods of local class can only access static and enum variables of the enclosing function. Non-
static variables of the enclosing function are not accessible inside local classes.
5) Local classes can access global types, variables and functions. Also, local classes can access other local
classes of same function.

Nested Classes in C++


A nested class is a class which is declared in another enclosing class. A nested class is a member and as such
has the same access rights as any other member. The members of an enclosing class have no special access
to members of a nested class; the usual access rules shall be obeyed.

Operator Overloading in C++


In C++, we can make operators to work for user defined classes. This means C++ has the ability to provide the
operators with a special meaning for a data type, this ability is known as operator overloading.
For example, we can overload an operator „+‟ in a class like String so that we can concatenate two strings by
just using +.
Other example classes where arithmetic operators may be overloaded are Complex Number, Fractional
Number, Big Integer, etc.
What is the difference between operator functions and normal functions?
Operator functions are same as normal functions. The only differences are, name of an operator function is
always operator keyword followed by symbol of operator and operator functions are called when the
corresponding operator is used.
Can we overload all operators?
Almost all operators can be overloaded except few. Following is the list of operators that cannot be overloaded.
Important points about operator overloading
1) For operator overloading to work, at least one of the operands must be a user defined class object.
2) Assignment Operator: Compiler automatically creates a default assignment operator with every
class. The default assignment operator does assign all members of right side to the left side and works
fine most of the cases (this behavior is same as copy constructor). See this for more details.
3) Conversion Operator: We can also write conversion operators that can be used to convert one
type to another type.
4) Any constructor that can be called with a single argument works as a conversion constructor, means it can
also be used for implicit conversion to the class being constructed.

Some important points to know about OOP:


1. OOP treats data as a critical element.
2. Emphasis is on data rather than procedure.
3. Decomposition of the problem into simpler modules.
4. Doesn‟t allow data to freely flow in the entire system, ie localized control flow.
5. Data is protected from external functions.

Advantages of OOPs –
 It models the real world very well.
 With OOP, programs are easy to understand and maintain.
 OOP offers code reusability. Already created classes can be reused without having to
write them again.
 OOP facilitates the quick development of programs where parallel development of
classes is possible.
 With OOP, programs are easier to test, manage and debug.

Disadvantages of OOP –
 With OOP, classes sometimes tend be over-generalised.
 The relations among classes become superficial at times.
 The OOP design is tricky and requires appropriate knowledge. Also, one needs to do
proper planning and design for OOP programming.
 To program with OOP, the programmer needs proper skills such as that of design,
programming and thinking in terms of objects and classes etc.

Java Programming Language


Java is one of the most popular and widely used programming language.
 Java has been one of the most popular programming language for many years.
 Java is Object Oriented. However it is not considered as pure object oriented as it
provides support for primitive data types (like int, char, etc)
 The Java codes are first compiled into byte code (machine independent code). Then
the byte code is run on Java Virtual Machine (JVM) regardless of the underlying architecture.
 Java syntax is similar to C/C++. But Java does not provide low level programming
functionalities like pointers. Also, Java codes are always written in the form of classes and objects.
 Java is used in all kind of applications like Mobile Applications (Android is Java based),
desktop applications, web applications, client server applications, enterprise applications and many
more.
 When compared with C++, Java codes are generally more maintainable because Java
does not allow many things which may lead bad/inefficient programming if used incorrectly. For
example, non-primitives are always references in Java. So we cannot pass large objects (like we can
do in C++) to functions, we always pass references in Java. One more example, since there are no
pointers, bad memory access is also not possible.
 When compared with Python, Java kind of fits between C++ and Python. The programs
written in Java typically run faster than corresponding Python programs and slower than C++. Like
C++, Java does static type checking, but Python does not.

Packages In Java
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
Packages are used for:
 Preventing naming conflicts. For example there can be two classes with name
Employee in two packages, college.staff.cse.Employee and college.staff.ee.Employee
 Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
 Providing controlled access: protected and default have package level access control.
A protected member is accessible by classes in the same package and its subclasses. A default
member (without any access specifier) is accessible by classes in the same package only.
 Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply write an import class
from existing packages and use it in our program. A package is a container of a group of related
classes where some of the classes are accessible are exposed and others are kept for internal
purpose.
We can reuse existing classes from the packages as many time as we need it in our program.
How packages work?
Package names and directory structure are closely related. For example if a package name
is college.staff.cse, then there are three directories, college, staff and cse such that cse is present
in staff and staff is present college. Also, the directory college is accessible
through CLASSPATH variable, i.e., path of parent directory of college is present in CLASSPATH. The
idea is to make sure that classes are easy to locate.
Package naming conventions : Packages are named in reverse order of domain names, i.e.,
org.geeksforgeeks.practice. For example, in a college, the recommended convention is
college.tech.cse, college.tech.ee, college.art.history, etc.
Adding a class to a Package : We can add more classes to a created package by using package
name at the top of the program and saving it in the package directory. We need a new java file to
define a public class, otherwise we can add the new class to an existing .java file and recompile it.
Subpackages: Packages that are inside another package are the subpackages. These are not
imported by default, they have to imported explicitly. Also, members of a subpackage have no access
privileges, i.e., they are considered as different package for protected and default access specifiers.
Types of packages:

Built-in Packages
These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math
operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and
support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.
User-defined packages
These are the packages that are defined by the user. First we create a directory myPackage (name
should be same as the name of the package). Then create the MyClass inside the directory with the
first statement being the package names.
Important points:
1. Every class is part of some package.
2. If no package is specified, the classes in the file goes into a special unnamed
package (the same unnamed package for all files).
3. All classes/interfaces in a file are part of the same package. Multiple files can
specify the same package name.
4. If package name is specified, the file must be in a subdirectory called name (i.e.,
the directory name must match the package name).
5. We can access public classes in another (named) package using: package-
name.class-name

Exceptions in Java
What is an Exception?
An exception is an unwanted or unexpected event, which occurs during the execution of a program i.e
at run time, that disrupts the normal flow of the program‟s instructions.
Error vs Exception
Error: An Error indicates serious problem that a reasonable application should not try to catch.
Exception: Exception indicates conditions that a reasonable application might try to catch.
Exception Hierarchy
All exception and errors types are sub classes of class Throwable, which is base class of
hierarchy.One branch is headed by Exception. This class is used for exceptional conditions that user
programs should catch. NullPointerException is an example of such an exception.Another
branch,Error are used by the Java run-time system(JVM) to indicate errors having to do with the run-
time environment itself(JRE). StackOverflowError is an example of such an error.

For checked vs unchecked exception, see Checked vs Unchecked Exceptions

How JVM handle an Exception?


Default Exception Handling : Whenever inside a method, if an exception has occurred, the method
creates an Object known as Exception Object and hands it off to the run-time system(JVM). The
exception object contains name and description of the exception, and current state of the program
where exception has occurred. Creating the Exception Object and handling it to the run-time system is
called throwing an Exception.There might be the list of the methods that had been called to get to the
method where exception was occurred. This ordered list of the methods is called Call Stack.Now the
following procedure will happen.
 The run-time system searches the call stack to find the method that contains block of
code that can handle the occurred exception. The block of the code is called Exception handler.
 The run-time system starts searching from the method in which exception occurred,
proceeds through call stack in the reverse order in which methods were called.
 If it finds appropriate handler then it passes the occurred exception to it. Appropriate
handler means the type of the exception object thrown matches the type of the exception object it can
handle.
 If run-time system searches all the methods on call stack and couldn‟t have found the
appropriate handler then run-time system handover the Exception Object to default exception
handler , which is part of run-time system. This handler prints the exception information in the
following format and terminates program abnormally.

 How Programmer handles an exception?
 Customized Exception Handling : Java exception handling is managed via five
keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program statements
that you think can raise exceptions are contained within a try block. If an exception occurs within the
try block, it is thrown. Your code can catch this exception (using catch block) and handle it in some
rational manner. System-generated exceptions are automatically thrown by the Java run-time system.
To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method
must be specified as such by a throws clause. Any code that absolutely must be executed after a try
block completes is put in a finally block

Points to remember :
 In a method, there can be more than one statements that might throw exception, So put
all these statements within its own try block and provide separate exception handler within
own catch block for each of them.
 If an exception occurs within the try block, that exception is handled by the exception
handler associated with it. To associate exception handler, we must put catch block after it. There can
be more than one exception handlers. Each catch block is a exception handler that handles the
exception of the type indicated by its argument. The argument, ExceptionType declares the type of the
exception that it can handle and must be the name of the class that inherits from Throwable class.
 For each try block there can be zero or more catch blocks, but only one finally block.
 The finally block is optional.It always gets executed whether an exception occurred in
try block or not . If exception occurs, then it will be executed after try and catch blocks. And if
exception does not occur then it will be executed after the try block. The finally block in java is used to
put important codes such as clean up code e.g. closing the file or closing the connection.

Multithreading in Java
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for
maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight
processes within a process.

Threads can be created by using two mechanisms :


1. Extending the Thread class
2. Implementing the Runnable Interface

Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the run() method
available in the Thread class. A thread begins its life inside run() method. We create an object of our
new class and call start() method to start the execution of a thread. Start() invokes the run() method on
the Thread object.
Thread Class vs Runnable Interface
1. If we extend the Thread class, our class cannot extend any other class because Java doesn‟t support
multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.

2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt
methods like yield(), interrupt() etc. that are not available in Runnable interface.

You might also like