Fundamentals of OOPs
Fundamentals of OOPs
Fundamentals of OOPs
It is the most popular programming model among developers. It is well suited for programs that are large,
complex, and actively updated or maintained. It simplifies software development and maintenance by
providing major concepts such as abstraction, inheritance, polymorphism, and encapsulation. These core
concepts support OOP.
Advantages of OOP:
Object-oriented programming has several advantages over procedural programming:
Pillars of OOPs
The major concepts that we have discussed above are known as pillars of OOPs. There are four pillars on
which OOP rests.
• Abstraction
• Encapsulation
• Inheritance
• Polymorphism
What is Procedural Programming?
• Basically, procedural programming revolves around a sequence of instructions given to the computer.
These sequences of instructions are known as procedures.
• Since the instructions are carried out in well-defined sequences, we say that procedural programming
takes a top-down approach.
• In procedural programming, we divide our instructions into smaller blocks of well-defined code.
These code blocks are known as functions, where each function performs a specific task.
• Writing a procedural program involves calling the right function at the right time, i.e., using the
appropriate function at the appropriate place within the larger code.
• These functions often take data and process them to give an output. However, unlike object-oriented
programming, we treat data and functions (procedure) as separate in procedural programming.
Features of Procedural Programming:
The procedural paradigm consists of the following elements:
Pre-defined Functions
They are often standardized instructions that are included in the programming language itself, usually in
standard libraries that are part of the language.
These functions are identified by name (say, printf, scanf, pow, etc.), and they each perform a specific task
such as taking user input, displaying output on the screen, carrying out mathematical operations, etc.
Developers don't need to code each and everything from scratch because pre-defined functions can automate
those tasks for us.
Local Variable
A variable is a named location in the computer memory that is used to store data. Local variables are those
that are declared within a local scope.
To clarify, a local scope is a closed block or subsection of the program. The variables and other named
entities defined inside that block are not valid outside of that block.
Hence, a function is also a local scope, i.e., variables defined inside a function are invalid outside that
function. Using a variable outside the function or local scope will cause the entire program to fail.
Global Variable
A global variable can be used throughout the whole program since it is declared outside of all the functions
and scopes that are defined inside the program.
Parameter Passing
Functions often work with data to give a certain result. Here, a function is like a machine that takes data as
input and spits out a single output.
We often supply such data input by passing them as parameters to a function. These parameters could be
variables, values, memory addresses, etc.
The supplied data can be either user input, values provided by the programmer, or results derived from some
other operation within the program.
Modularity
This is the practice of using different functions and procedures simultaneously to accomplish a single,
greater task. Each procedure performs a specific task that is different from other functions. But combining
their results leads to accomplishing the greater task.
Top-Down Approach
In this approach, the program is divided into smaller chunks that are executed in a sequential manner.
Benefits of Procedural Programming
There are many benefits to procedural programming, some of which are
Simplicity: Procedural programming is easy to understand and code due to its simple structure.
Reusable Code: Functions can be reused within the program again and again. This makes coding easier. It
also reduces the length of the code and the time needed to write the entire program.
Easy Testability: The simplicity of procedural programming makes the code easy to test and debug. The
shorter program length and the use of reusable code are great for quickly identifying sources of errors.
General Programming: The procedural paradigm is great for general use and for smaller projects.
Smaller Memory Requirement: Procedural programming utilizes less memory than other paradigms. This
increases the efficiency of our program.
Team-Friendly: Multiple programmers can work on the same project simultaneously, with each
programmer coding a different function. These functions can then be combined into a single project.
Accessibility: There are a lot of resources available to learn procedural programming since it is often the
first paradigm that is taught to beginners.
Limitations of Procedural Programming
Along with the advantages, there are many disadvantages to procedural programming. Some of them are
Focused on Operations: Procedural programming focuses on functions and procedures more than data.
This method is unsuitable for projects where data is important.
No Data Security: Data is exposed and accessible to multiple procedures in procedural programming. Thus,
it is unsuitable for projects where we must protect data.
No Portability: With procedural programming, code can be reused within a single project. However, they
cannot be exported to other projects. So we need to rewrite a lot of code when working on other projects.
Cannot Model the Real World: Since procedures are prioritized over data and objects, this paradigm
cannot model the real world properly.
Unsuitable for Complexity: Procedural programming is unsuitable for creating large-scale and complex
applications.
What is Procedural Programming Used For?
While Object-Oriented Programming (OOP) remains the most popular programming paradigm today,
procedural programming still has many uses. You can use this paradigm to
• create compilers, operating systems, kernels, etc.,
• code system software for devices and embedded systems,
• code server-side applications as a web developer.
Since many programming languages allow you to code in both procedural and object-oriented paradigms,
you can even combine these paradigms in independent programs within the same codebase.
This is because OOP is suitable for some problems, while procedural programming is suitable for others.
And there are even problems that are unsuitable for both of these paradigms and may need functional
programming or some other paradigm.
Procedural Programming vs. Object-Oriented Programming
Functions and variables are the primary Classes and objects are the primary programming
programming tools. tools.
It cannot model the real world effectively. It can model the real world effectively.
It is not suitable for large and complex apps. It is suitable for large and complex apps.
C, Basic, Fortran, Pascal, etc., are examples of C++, Java, Python, JavaScript, etc., are examples of
procedural languages. object-oriented languages.
OOPS concept in Java: Object-Oriented Programming is a methodology or paradigm to design a
program using classes and objects. It simplifies software development and maintenance by providing some
concepts:
➢ Object
➢ Class
➢ Inheritance
➢ Polymorphism
➢ Abstraction
➢ Encapsulation
Object:
• Any entity that has state and behavior is known as an object. For example, a chair, pen, table, keyboard,
bike, etc. It can be physical or logical.
• An Object can be defined as an instance of a class. An object contains an address and takes up some
space in memory. Objects can communicate without knowing the details of each other's data or code.
The only necessary thing is the type of message accepted and the type of response returned by the
objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as behaviors like
wagging the tail, barking, eating, etc.
Class:
Example:
• When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance.
• It is an important part of OOPs (Object Oriented programming system).
• It provides code reusability.
• It is used to achieve runtime polymorphism.
• Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
• The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent class.
Moreover, you can add new methods and fields in your current class also.
1. Single-level inheritance
2. Multi-level Inheritance
3. Multiple Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance
In java programming, multiple and hybrid inheritance is supported through interface only.
Polymorphism
• 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.
• 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 possesses different behavior in different
situations. This is called polymorphism.
• Polymorphism is considered one of the important features of Object-Oriented Programming.
Polymorphism 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.
• In Java, we use method overloading and method overriding to achieve polymorphism.
In Java polymorphism is mainly divided into two types:
1. Compile-time Polymorphism
2. Runtime Polymorphism
Abstraction
• Hiding internal or background details and showing the essential features is known as abstraction.
• For example, phone call, we don't know the internal processing.
• In Java, we use abstract class and interface to achieve abstraction.
Encapsulation
• Binding (or wrapping) code and data together into a single unit are known as encapsulation.
• For example, a capsule, it is wrapped with different medicines.
Method in Java
In general, a method is a way to perform some task. Similarly, the method in Java is a collection of
instructions that performs a specific task. It provides the reusability of code. We can also easily modify code
using methods. In this section, we will learn what is a method in Java, types of methods, method
declaration, and how to call a method in Java.
• A method is a block of code or collection of statements or a set of code grouped together to perform
a certain task or operation. It is used to achieve the reusability of code. We write a method once and
use it many times. We do not require to write code again and again.
• It also provides the easy modification and readability of code, just by adding or removing a chunk
of code. The method is executed only when we call or invoke it.
What is Java?
• Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the
U.S.A., France, Germany, Romania, etc.
• In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
Why had they choose the name Java for Java language?
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so unique,
most of the team members preferred Java than other names.
Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of
espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.
Java is popular because it has been designed for ease of use. Some reasons developers continue to choose
Java over other programming languages include:
Java has been around for a long time, so many learning resources are available for new programmers.
Detailed documentation, comprehensive books, and courses support developers through the learning curve.
In addition, beginners can start writing code in Core Java before moving to Advanced Java.
Inbuilt functions and libraries
When using Java, developers don’t need to write every new function from scratch. Instead, Java provides a
rich ecosystem of in-built functions and libraries to develop a range of applications.
Java has many active users and a community that can support developers when they face coding challenges.
The Java platform software is also maintained and updated regularly.
Java offers various tools to support automated editing, debugging, testing, deployment, and change
management. These tools make Java programming time and cost-efficient.
Platform Independent
Java code can run on any underlying platform like Windows, Linux, iOS, or Android without rewriting. This
makes it especially powerful in today’s environment, where we want to run applications on multiple devices.
Security
Users can download untrusted Java code over a network and run it in a secure environment in which it
cannot do any harm. Untrusted code cannot infect the host system with a virus nor can it read or write files
from the hard drive. The security levels and restrictions in Java are also highly configurable.
Features of Java:
The primary objective of Java programming language creation was to make it portable, simple and secure
programming language. Apart from this, there are also some excellent features which play an important role
in the popularity of this language. The features of Java are also known as Java buzzwords.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture Neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun
Microsystem, Java language is a simple programming language because:
• Java syntax is based on C++ (so easier for programmers to learn it after C++).
• Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
• There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in
Java.
Object-Oriented
1. Object
2. Class
3. Inherritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc. which are compiled
into platform specific machines while Java is a write once, run anywhere language. A platform is the hardware
or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-based
platform.
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS, etc.
Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent
code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
• Internal data management
• Automated memory management
• Error detection and handling
• Secure garbage collection
• Private keywords
• Fool proof data type checking
Robust
Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the size of
primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of memory
for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.
Interpreted
In programming languages, you have learned that they use either the compiler or an interpreter, but Java
programming language uses both a compiler and an interpreter. Java programs are compiled to generate
bytecode files then JVM interprets the bytecode file during execution. Along with this JVM also uses a JIT
(Just-in-Time) compiler (it increases the speed of execution).
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any
implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to
native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language
that is why it is slower than compiled languages, e.g., C, C++, etc.
Distributed
Java is distributed because it facilitates users to create distributed applications in Java. RMI (Remote Method
Invocation) and EJB (Enterprise Java Beans) are used for creating distributed applications. This feature of
Java makes us able to access files by calling the methods from any machine on the internet.
Multi-threaded
Thread is a light-weight and independent subprocess of a running program (i.e, process) that shares resources.
And when multiple threads run simultaneously is called multithreading. In many applications, you have seen
multiple tasks running simultaneously, for example, Google Docs where while typing text, the spell check and
autocorrect tasks are running. We can write Java programs that deal with many tasks at once by defining
multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web applications, etc.
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are loaded on demand.
It also supports functions from its native languages, i.e., C and C++.
✓ Java supports dynamic compilation and automatic memory management (garbage collection).
There are mainly 4 types of applications that can be created using Java programming:
1. Standalone Application
2. Web Application
3. Enterprise Application
4. Mobile Application
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These are
traditional software that we need to install on every machine. Examples of standalone application are Media
player, antivirus, etc. AWT (Abstract Window Toolkit) and Swing are used in Java for creating standalone
applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application. Web
application is a client server software application which is run by the client. Web application includes mails,
online retail sales, Wikipedia information etc. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
technologies are used for creating web applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an enterprise
application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used for
creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android and Java
ME are used for creating mobile applications.
It is a Java programming platform. It includes Java programming APIs such as java.lang, java.io, java.net,
java.util, java.sql, java.math etc. It includes core topics like OOPs, String, Regex, Exception, Inner classes,
Multithreading, I/O Stream, Networking, AWT, Swing, Reflection, Collection, etc.
It is an enterprise platform that is mainly used to develop web and enterprise applications. It is built on top of
the Java SE platform. It includes topics like Servlet, JSP, Web Services, EJB, JPA(Java Persistence API),
etc.
4) JavaFX
It is used to develop rich internet applications. It uses a lightweight user interface API(Application
Programming Interface).
What is JVM?
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it doesn't physically
exist. It is a specification that provides a runtime environment in which Java bytecode can be executed. It can
also run those programs which are written in other languages and compiled to Java bytecode.
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
What is JRE?
• JRE (Java Runtime Environment) is a software package that provides Java class libraries, Java
Virtual Machine (JVM), and other components that are required to run Java applications.
• The Java Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM. It
physically exists. It contains a set of libraries + other files that JVM uses at runtime.
• JRE is the superset of JVM.
What is JDK?
• JDK (Java Development Kit) is a software development kit required to develop applications in Java.
When you download JDK, JRE is also downloaded with it.
• JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically
exists.
• It contains JRE + development tools.
Normal Program:
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}
}
Example explained
Every line of code that runs in Java must be inside a class. In our example, we named the class Main. A
class should always start with an uppercase first letter.
➢ The name of the java file must match the class name. When saving the file, save it using the class
name and add ".java" to the end of the filename.
The main() method is required and you will see it in every Java program.
System.out.println()
Inside the main() method, we can use the println() method to print a line of text to the screen:
System.out.println("Hello World");
The curly braces {} marks the beginning and the end of a block of code.
• System is a built-in Java class that contains useful members, such as out, which is short for "output".
• The println() method, short for "print line", is used to print a value to the screen (or a file).
Double Quotes
When you are working with text, it must be wrapped inside double quotations marks " ".
The only difference is that it does not insert a new line at the end of the output:
Java Comments
Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent
execution when testing alternative code.
• Single-line Comments
Any text between // and the end of the line is ignored by Java (will not be executed).
• Multi-line Comments
Data types specify the different sizes and values that can be stored in the variable. There are two types of data
types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Variable in Java:
A variable is a container which holds the value while the java program is executed. A variable is the name of
a reserved area allocated in memory. In other words, it is a name of the memory location. It is a combination
of "vary + able" which means its value can be changed. A variable is assigned with a data type.
1. Local
2. Instance
3. Static
Syntax:
datatype variable_name = value;
Example:
public class Main {
public static void main(String[] args) {
int myNum = 100; //create variable
System.out.println(myNum);
}
}
You can also declare a variable without assigning the value, and assign the value later.
public class Main {
public static void main(String[] args) {
int myNum;
myNum = 150;
System.out.println(myNum);
}
}
Final Variables
If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare
the variable as "final" or "constant", which means unchangeable and read-only)
Types of Variables
• local variable
• instance variable
• static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance variable. It
is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a single copy
of the static variable and share it among all the instances of the class. Memory allocation for static variables
happens only once when the class is loaded in the memory.
Java Expressions
A Java expression consists of variables, operators, literals, and method calls.
int score;
score = 90;
Here, score = 90 is an expression that returns an int.
Operators in Java
There are many types of operators in Java which are given below:
• Unary Operator
• Arithmetic Operator
• Shift Operator
• Relational Operator
• Bitwise Operator
• Logical Operator
• Ternary Operator
• Assignment Operator
The Java unary operators require only one operand. It acts on single operand. Unary operators are used to
perform various operations i.e.:
a) Increment Operator
b) Decrement Operator
Increment Operator:
It increases the value of variable by one. It is denoted as (++). It is also two types.
I. Pre-increment
II. Post-increment
Decrement Operator:
It decreases the value of variable by one. It is denoted as (--). It is also two types.
I. Pre-decrement
II. Post-decrement
Example-1:
int x=10;
System.out.println(++x); //12
Example-2:
int a=10;
int b=10;
Arithmetic Operator: