CHPT 1 - What Is OOPs Concept

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

Chapter 1

What is OOPs Concept?


Object-oriented programming is a core of Java Programming, which is
used for designing a program using classes and objects. OOPs, can also
be characterized as data controlling for accessing the code. In this
approach, programmers define the data type of a data structure and the
operations that are applied to the data structure.

What is OOPs in java?


OOps in java is to improve code readability and reusability by defining a
Java program efficiently. The main principles of object-oriented
programming are abstraction, encapsulation, inheritance, and
polymorphism. These concepts aim to implement real-world entities in
programs.

List of OOPs Concepts in Java


● Objects
● Classes
● Object
● Class
● Abstraction
● Inheritance
● Polymorphism
● Encapsulation
What are Objects?
Objects are always called instances of a class which are created from a
class in java or any other language. They have states and behaviour.

These objects always correspond to things found in the real world, i.e.,
real entities. So, they are also called run-time entities of the world. These
are self–contained which consists of methods and properties which make
data useful. Objects can be both physical and logical data. It contains
addresses and takes up some space in memory. Some examples of
objects are a dog, chair, tree etc.

When we treat animals as objects, it has states like colour, name, breed
etc., and behaviours such as eating, wagging the tail etc.

Suppose, we have created a class called My book, we specify the class


name followed by the object name, and we use the keyword new.
Object Example 1:

Public class Mybook {


int x=10;
Public static void main (String args []) {
Mybook Myobj= new Mybook ();
System.out.println(MyObj.x);
}
}
In the above example, a new object is created, and it returns the value of
x which may be the number of books.

Mybook Myobj= new Mybook ();

This is the statement used for creating objects.

System.out.println(Myobj.x);

This statement is used to return the value of x of an object.

We can also create multiple objects in the same class and we can create
in one class and access it in another class. This method is used for better
organization of classes and always remember that name of the java file
and the class name remains the same.

Example 2:

The below example shows how multiple objects are created in the same
class and how they are accessed from another class.

● Mybook.java
Public class Mybook {
int x=10;
1 int y=8;
}

● Count.java

Class Count {
Public static void main (String [] args)
{
Mybook myobj1 = new myobj1();
Mybook myobj2 = new myobj2();
System.out.println (myobj1.x);
System.out.println (myobj2.y);
}
}

When this program is compiled, it gives the result as 10, and 8


respectively.

What are Classes?


Classes are like object constructors for creating objects. The collection
of objects is said to be a class. Classes are said to be logical quantities.
Classes don’t consume any space in the memory. Class is also called a
template of an object. Classes have members which can be fields,
methods and constructors. A class has both static and instance
initializers.

A class declaration consists of:

1. Modifiers: These can be public or default access.


2. Class name: Initial letter.
3. Superclass: A class can only extend (subclass) one parent.
4. Interfaces: A class can implement more than one interface.
5. Body: Body surrounded by braces, { }.
A class keyword is used to create a class. A simplified general form of
the class definition is given below:

class classname {
type instance variable 1;
type instance variable 2;
.
.
.
type instance variable n;
type methodname 1 (parameter list) {
// body od method
}
type methodname 2 (parameter list) {
// body od method
}
type methodnamen (parameter list) {
// body od method
}
}
The variables or data defined within a class are called instance variables.
Code is always contained in the methods. Therefore, the methods and
variables defined within a class are called members of the class. All the
methods have the same form as the main () these methods are not
specified as static or public.

What is Abstraction?
Data Abstraction is the property by virtue of which only the essential
details are displayed to the user. The trivial or non-essential units are not
displayed to the user.
Ex: A car is viewed as a car rather than its individual components.

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 behaviors of an object differentiate it from other
objects of similar type and also help in classifying/grouping the object.

Demonstration of Abstract class

//abstract class
abstract class GFG{
//abstract methods declaration
abstract void add();
abstract void mul();
abstract void div();
}
What is Inheritance?
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. We
are achieving inheritance by using extends keyword. Inheritance is also
known as “is-a” relationship.

Let us discuss some frequently used important terminologies:

● Superclass: The class whose features are inherited is known as


superclass (also known as base or parent class).
● Subclass: The class that inherits the other class is known as subclass
(also known as derived or extended 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.

Demonstration of Inheritance :

//base class or parent class or super class


class A{
//parent class methods
void method1(){}
void method2(){}
}

//derived class or child class or base class


class B extends A{ //Inherits parent class methods
//child class methods
void method3(){}
void method4(){}
}
What is Polymorphism?
It refers to the ability of object-oriented programming languages to
differentiate between entities with the same name efficiently. This is
done by Java with the help of the signature and declaration of these
entities. The ability to appear in many forms is called polymorphism.
E.g:

sleep(1000) //millis

sleep(1000,2000) //millis,nanos

// Java program to Demonstrate Polymorphism


// This class will contain
// 3 methods with same name,
// yet the program will
// compile & run successfully
public class Sum {

// Overloaded sum().
// This sum takes two int parameters
public int sum(int x, int y)
{
return (x + y);
}

// Overloaded sum().
// This sum takes three int parameters
public int sum(int x, int y, int z)
{
return (x + y + z);
}

// Overloaded sum().
// This sum takes two double parameters
public double sum(double x, double y)
{
return (x + y);
}

// Driver code
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

Output
30
60
31.0
Polymorphism in Java is mainly of 2 types:
1. Overloading
2. Overriding

What is Encapsulation?
It is defined as the wrapping up of data under a single unit. It is the
mechanism that binds together the code and the data it manipulates.
Another way to think about encapsulation is that it is a protective shield
that prevents the data from being accessed by the code outside this
shield.
● Technically, in encapsulation, the variables or the data in a class is
hidden from any other class and can be accessed only through any
member function of the class in which they are declared.
● In encapsulation, the data in a class is hidden from other classes,
which is similar to what data-hiding does. So, the terms
“encapsulation” and “data-hiding” are used interchangeably.
● Encapsulation can be achieved by declaring all the variables in a
class as private and writing public methods in the class to set and get
the values of the variables.

Demonstration of Encapsulation:

//Encapsulation using private modifier


//Employee class contains private data called employee id and employee
name
class Employee {
private int empid;
private String ename;
}
Advantages of OOPs Concept
Some of the advantages are:

● Re-usability
When we say re-usability, it means that “write once, use it multiple
times” i.e., reusing some facilities rather than building it again and
again, which can be achieved by using class. We can use it n number of
times whenever required.

● Data redundancy
It is one of the greatest advantages in oops. This is the condition which
is created at the data storage when the same piece of data is held at two
different places. If we want to use similar functionality in multiple
classes, we can just write common class definitions for similar
functionalities by inheriting them.

● Code maintenance
It is easy to modify or maintain existing code as new objects which can
be created with small differences from the existing ones. This helps
users from doing rework many times and modifying the existing codes
by incorporating new changes to it.
● Security
Data hiding and abstraction are used to filter out limited exposure which
means we are providing only necessary data to view as we maintain
security.

● Design benefits
The designers will have a long and more extensive design phase, which
results in better designs. At a point of time when the program has
reached critical limits, it will be easier to program all non-oops
separately.

● Easy troubleshooting
Using encapsulation objects is self-constrained. So, if developers face
any problem easily it can be solved. And there will be no possibility of
code duplicity.

● Flexibility
● Problem-solving

Disadvantages of OOPs Concept


● Effort – A lot of work is put into creating these programs.
● Speed – These programs are slower compared to other programs.
● Size – OOPs programs are bigger when compared to other
programs.
Differences between Object-Oriented Programming,
Procedural Oriented Programming?

Object-oriented programming Procedure oriented programming

It is object-oriented. It is structured and oriented.

It is divided into small parts called


It follows a bottom-up approach.
functions.

hese are divided into small parts called objects. It follows a top-down approach.

These have specifiers like public, private,


There are no access specifiers.
and protected.

Adding new functions or data is easy. Adding new data and functions is not easy.

It provides data hiding and it is more secure. This is less secure.

Overloading is possible. Overloading is not possible.

Examples are c++, java, python etc. Examples FORTRAN, Cobol etc.
Basic programming constructs:EXP 1
❖ This program will try to print “Hello World” 5 times.

class whileLoopDemo {
public static void main(String args[])
{
// initialization expression
int i = 1;

// test expression
while (i < 6) {
System.out.println("Hello World");

// update expression
i++;
}
}
}

Output
Hello World
Hello World
Hello World
Hello World
Hello World

❖ This program will find the summation of numbers from 1 to 10.


class whileLoopDemo {
public static void main(String args[])
{
int x = 1, sum = 0;

// Exit when x becomes greater than 4


while (x <= 10) {
// summing up x
sum = sum + x;

// Increment the value of x for


// next iteration
x++;
}
System.out.println("Summation: " + sum);
}
}
Output
Summation: 55

❖ This program will print 1 to 10


class GFG {
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
Output
1
2
3
4
5
6
7
8
9
10

❖ This program will try to print “Hello World” 5 times.


class forLoopDemo {
public static void main(String args[])
{
// Writing a for loop
// to print Hello World 5 times
for (int i = 1; i <= 5; i++)
System.out.println("Hello World");
}
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World

❖ The following program prints the sum of x ranging from 1 to 20.


class forLoopDemo {
public static void main(String args[])
{
int sum = 0;

// for loop begins


// and runs till x <= 20
for (int x = 1; x <= 20; x++) {
sum = sum + x;
}
System.out.println("Sum: " + sum);
}
}
Output
Sum: 210

❖ This program will try to print “Hello World” 5 times.


class GFG {

// Main driver method


public static void main(String args[])
{

// Declaring and initialization expression


int i = 1;

// Do-while loop
do {

// Body of do-while loop


// Print statement
System.out.println("Hello World");

// Update expression
i++;
}

// Test expression
while (i < 6);
}
}

Output:
Hello World
Hello World
Hello World
Hello World
Hello World

You might also like