Unit I Notes
Unit I Notes
There are some basic concepts that act as the building blocks of OOPs i.e.
1. Class
2. Objects
3. Encapsulation
4. Abstraction
5. Polymorphism
6. Inheritance
7. Message Passing
Class
A Class is a user-defined data type that has data members and member functions.
Data members are the data variables and member functions are the functions used to
manipulate these variables together these data members and member functions define
the properties and behavior of the objects in a Class.
In the above example of class Car, the data member will be speed limit, mileage, etc
and member functions can apply brakes, increase speed, etc.
Class is a blueprint representing a group of objects which shares some common properties
and behaviors.
Object
Objects take up space in memory and have an associated address. When a program is
executed the objects interact by sending messages to one another. 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 the type of
response returned by the objects.
Encapsulation
In normal terms, Encapsulation is defined as wrapping up data and information under a single
unit. In Object-Oriented Programming, Encapsulation is defined as binding together the data
and the functions that manipulate them. 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”.
Encapsulation
Encapsulation also leads to data abstraction or data hiding. Using encapsulation also hides
the data. In the above example, the data of any of the sections like sales, finance, or accounts
are hidden from any other section.
Abstraction
Data abstraction is one of the most essential and important features of object-oriented
programming. Abstraction means displaying only essential information and hiding the details.
Data abstraction refers to providing only essential information about the data to the outside
world, hiding the background details or implementation. Consider a real-life example of a
man driving a car. The man only knows that pressing the accelerator will increase the speed
of the car or applying brakes will stop the car but he does not know how on pressing the
accelerator the speed is actually increasing, he does not know about the inner mechanism of
the car or the implementation of an accelerator, brakes, etc. in the car. This is what
abstraction is.
Abstraction using Classes: We can implement Abstraction using classes. The class
helps us to group data members and member functions using available access
specifiers. A Class can decide which data member will be visible to the outside world
and which is not.
Abstraction in Header files: One more type of abstraction can be header files. For
example, consider the pow() method present in math.h header file. Whenever we need
to calculate the power of a number, we simply call the function pow() present in the
math.h header file and pass the numbers as arguments without knowing the
underlying algorithm according to which the function is actually calculating the
power of numbers.
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. A man at the same time is a father, a
husband, and an employee. So the same person possesses different behavior in different
situations. This is called polymorphism. An operation may exhibit different behaviors in
different instances. The behavior depends upon the types of data used in the operation.
Example: Suppose we have to write a function to add some integers, sometimes there are 2
integers, and sometimes there are 3 integers. We can write the Addition Method with the
same name having different parameters, the concerned method will be called according to
parameters.
Polymorphism
Inheritance
The capability of a class to derive properties and characteristics from another class is called
Inheritance. Inheritance is one of the most important features of Object-Oriented
Programming.
Sub Class: The class that inherits properties from another class is called Sub class or
Derived Class.
Super Class: The class whose properties are inherited by a sub-class is called Base
Class or Superclass.
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.
Example: Dog, Cat, Cow can be Derived Class of Animal Base Class.
Inheritance
Message Passing
Objects communicate with one another by sending and receiving information. A message for
an object is a request for the execution of a procedure and therefore will invoke a function in
the receiving object that generates the desired results. Message passing involves specifying
the name of the object, the name of the function, and the information to be sent.
We can build the programs from standard working modules that communicate with
one another, rather than having to start writing the code from scratch which leads to
saving of development time and higher productivity,
OOP language allows to break the program into the bit-sized problems that can be
solved easily (one object at a time).
The new technology promises greater programmer productivity, better quality of
software and lesser maintenance cost.
It is very easy to partition the work in a project based on objects.
It is possible to map the objects in problem domain to those in the program.
The principle of data hiding helps the programmer to build secure programs which
cannot be invaded by the code in other parts of the program.
By using inheritance, we can eliminate redundant code and extend the use of existing
classes.
Message passing techniques is used for communication between objects which makes
the interface descriptions with external systems much simpler.
The data-centered design approach enables us to capture more details of model in an
implementable form.
Disadvantages of OOP
The length of the programmes developed using OOP language is much larger than the
procedural approach. Since the programme becomes larger in size, it requires more
time to be executed that leads to slower execution of the programme.
We can not apply OOP everywhere as it is not a universal language. It is applied only
when it is required. It is not suitable for all types of problems.
Programmers need to have brilliant designing skill and programming skill along with
proper planning because using OOP is little bit tricky.
OOPs take time to get used to it. The thought process involved in object-oriented
programming may not be natural for some people.
Everything is treated as object in OOP so before applying it we need to have excellent
thinking in terms of objects.
Complex systems are challenging to model because variables have different specifications.
Complex systems stimulation requires precise modeling and knowledge of the interaction.
OOP offers a suitable method for streamlining these complex structures.
3. AI Expert System
These are computer programs created to address complicated issues that are much beyond the
human brain's capabilities. The following characteristics of OOP, which aid in developing an
AI expert system, include dependability, high responsiveness, high performance, and
understandability.
4. Object-oriented Database
To preserve the object's integrity and identity, databases maintain a close correlation between
database objects and their counterparts in the physical world.
A neural network is a collection of algorithms that aims to identify underlying links in a piece
of data using a method that imitates how the human brain functions.
In parallel programming, an issue is split into smaller subproblems that may all be worked on
simultaneously utilizing different computing resources. Oops, are used to streamline the
procedure by simplifying the network's capacity for approximation and prediction.
6. Client Server System
OOP can be used in CAD software to develop classes that represent different design
components including lines, curves, surfaces, and solids. The class's relationships,
behaviours, and properties can be described through attributes and methods. Code reuse and
modularity are made possible by inheritance, which can be used to construct relationships
between various sorts of design elements.
9. Software Development
OOP facilitates modular and reusable code, making it ideal for developing complex software
systems. It enhances code organization, maintenance, and collaboration among developers.
OOP enables the creation of user-friendly interfaces with features like encapsulation,
inheritance, and polymorphism. Frameworks like JavaFX and Qt utilize OOP concepts for
GUI development.
Java
Java is a general purpose, high-level programming language developed by James Gosling and
his team at Sun Microsystems. The Java programming language was developed by a small
team of engineers, known as the Green Team, who initiated the language in 1991. The
language was originally called OAK, and at the time it was designed for handheld devices and
set-top boxes. Oak was unsuccessful and in 1995 Sun changed the name to Java and modified
the language to take advantage of the burgeoning World Wide Web.
Later, in 2009, Oracle Corporation acquired Sun Microsystems and took ownership of two
key Sun software assets: Java and Solaris.
Features of Java
The prime reason behind creation of Java was to bring portability and security feature into a
computer language. Beside these two major features, there were many other features that
played an important role in moulding out the final form of this outstanding language. Those
features are:
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to understand. The
confusing and ambiguous concepts of C++ are either left out in Java or they have been re-
implemented in a cleaner way.
Eg : Pointers and Operator Overloading are not there in java but were an important part of C+
+.
2) Object Oriented
In java everything is Object which has some data and behaviour. Java can be easily extended
as it is based on Object Model.
3) Robust
Java makes an effort to eliminate error prone codes by emphasizing mainly on compile time
error checking and runtime checking. But the main areas which Java improved were Memory
Management and mishandled Exceptions by introducing automatic Garbage
Collector and Exception Handling.
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are compiled into platform
specific machines. Java is guaranteed to be write-once, run-anywhere language.
On compilation Java program is compiled into bytecode. This bytecode is platform
independent and can be run on any machine, plus this bytecode format also provide security.
Any machine with Java Runtime Environment can run Java Programs.
5) Secure
When it comes to security, Java is always the first choice. With java secure features it enable
us to develop virus free, temper free system. Java program always runs in Java runtime
environment with almost null interaction with system OS, hence it is more secure.
6) Multi Threading
Java multithreading feature makes it possible to write program that can do many tasks
simultaneously. Benefit of multithreading is that it utilizes same memory and other resources
to execute multiple threads at the same time, like While typing, grammatical errors are
checked along.
7) Architectural Neutral
Compiler generates bytecodes, which have nothing to do with a particular computer
architecture, hence a Java program is easy to intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation dependent features.
Everything related to storage is predefined, example: size of primitive data types
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled language like C or C+
+. But, Java enables high performance with the use of just-in-time compiler.
Comparison among Java, C, C++
Type of As it connects the gaps C++ is a high-level Due to the fact that Java
language between machine-level language. code is converted into
and high-level machine language via a
languages, C is a compiler or interpreter,
middle-level language. Java is a high-level
language.
As discussed earlier, first the Java code is compiled by the Java compiler and generates the
bytecode. This bytecode will be stored in class files. Java Virtual Machine (JVM) is unique
for each platform. Though JVM is unique for each platform, all interpret the same bytecode
and convert it into machine code required for its own platform and this machine code will be
directly executed by the machine in which java program runs. This makes Java platform
independent and portable.
Let’s make it more clear with the help of the following diagram. Here the same compiled
Java bytecode is interpreted by two different JVMS to make it run in Windows and Linux
platforms.
4. Java Runtime Environment (JRE) and Java Architecture in Detail
Java Runtime Environment contains JVM, class libraries and other supporting components.
The Java source code is compiled into bytecode by Java compiler. This bytecode will be
stored in class files. During runtime, this bytecode will be loaded, verified and JVM
interprets the bytecode into machine code which will be executed in the machine in which the
Java program runs.
As we discussed earlier when the Java program is executed, the byte code is interpreted by
JVM. But this interpretation is a slower process. To overcome this difficulty, JRE include the
component JIT compiler. JIT makes the execution faster.
If the JIT Compiler library exists, when a particular bytecode is executed first time, JIT
complier compiles it into native machine code which can be directly executed by the machine
in which the Java program runs. Once the byte code is recompiled by JIT compiler, the
execution time needed will be much lesser. This compilation happens when the byte code is
about to be executed and hence the name “Just in Time”.
Once the bytecode is compiled into that particular machine code, it is cached by the JIT
compiler and will be reused for the future needs. Hence the main performance improvement
by using JIT compiler can be seen when the same code is executed again and again because
JIT make use of the machine code which is cached and stored.
6. Garbage Collection
Garbage collection is a process by which Java achieves better memory management. As you
know, in object oriented programming, objects communicate to each other by passing
messages.
Whenever an object is created, there will be some memory allocated for this object. This
memory will remain as allocated until there are some references to this object. When there is
no reference to this object, Java will assume that this object is not used anymore. When
garbage collection process happens, these objects will be destroyed and memory will be
reclaimed.
Garbage collection happens automatically. There is no way that you can force garbage
collection to happen. There are two methods “System.gc()” and “Runtime.gc()” through
which you can make request for garbage collation. But calling these methods also will not
force garbage collection to happen and you cannot make sure when this garbage collection
will happen.
Java is an Object oriented language. Every java program imports packages which are provides necessary
classes and interfaces.
For example:
import java.util.*;
import java.io.*;
After import statement, every java program starts with the declaration of the class. A program may have one
or more classes. A class declaration starts with the keyword class, followed by the identifier or name of the
class. Giving the name of a package at the top is optional. Class declaration contains name of the class and
body of the class. The body of the class may consist of several statements and is enclosed between the
braces {}.
Here:
public is access specifier. This class is accessible to any outside code. Otherwise, the class is accessible to
only same package classes. class is a keyword of java language which is used to declare the class.
The class body starts with the left brace { and ends with the right closing brace }.
// are comments which are neglected by the compiler.
A class body may comprise statements for declaration of variables. constants, expressions, and methods.
Here java command calls the Java interpreter which executes the Start.class (bytecode of Start.java).
Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program. It improves the readability of the program. Whatever we write in the documentation
section, the Java compiler ignores the statements during the execution of the program. To
write the statements in the documentation section, we use comments. The comments may be
single-line, and multi-line comments.
Single-line Comment: It starts with a pair of forwarding slash (//). For example:
//First Java Program
Multi-line Comment: It starts with a /* and ends with */. We write between these
two symbols. For example:
/*It is an example of
multiline comment*/
Package Declaration
The package declaration is optional. It is placed just after the documentation section. In this
section, we declare the package name in which the class is placed. Note that there can be
only one package statement in a Java program. It must be defined before any class and
interface declaration. It is necessary because a Java class can be placed in different packages
and directories based on the module they are used. For all these classes package belongs to a
single parent directory. We use the keyword package to declare the package name. For
example:
Interface Section
It is an optional section. We can create an interface in this section if required. We use the
interface keyword to create an interface. An interface is a slightly different from the class. It
contains only constants and method declarations. Another difference is that it cannot be
instantiated. We can use interface in classes by using the implements keyword. An interface
can also be used with other interfaces by using the extends keyword. For example:
interface car
{
void start();
void stop();
}
Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class, we
cannot create any Java program. A Java program may conation more than one class
definition. We use the class keyword to define the class. The class is a blueprint of a Java
program. It contains information about user-defined methods, variables, and constants. Every
Java program has at least one class that contains the main() method. For example:
class Student //class definition
{
}
CheckPalindromeNumber.java
/*Program name: Palindrome*/
//Author's name: Mathew
/*Palindrome is number or string that will remains the same
When we write that in reverse order. Some example of
palindrome is 393, 010, madam, etc.*/
//imports the Scanner class of the java.util package
import java.util.Scanner;
//class definition
public class CheckPalindromeNumber
{
//main method
public static void main(String args[])
{
//variables to be used in program
int r, s=0, temp;
int x; //It is the number variable to be checked for palindrome
Scanner sc=new Scanner(System.in);
System.out.println("Enter the number to check: ");
//reading a number from the user
x=sc.nextInt();
//logic to check if the number id palindrome or not
temp=x;
while(x>0)
{
r=x%10; //finds remainder
s=(s*10)+r;
x=x/10;
}
if(temp==s)
System.out.println("The given number is palindrome.");
else
System.out.println("The given number is not palindrome.");
}
}
Elements or Tokens in Java Programs
Java program contains different types of elements like white spaces, comments and tokens. A token is the
smallest program element which is recognized by the compiler and which treats them as defined for the
compiler. A program is a set of tokens which comprise the following elements:
Keywords: These are special words defined in Java and represent a set of instructions.
• The keywords represent groups of instructions for the compiler.
• These are special tokens that have a predefined meaning and their use is restricted.
• keywords cannot be used as names of variables, methods, classes, or packages.
• These are written in the lower case.
• E.g. class, int, float, for, while, if, else etc.